十四 687. 扫雷 (Flood Fill)

687. 扫雷 (Flood Fill)
image

思路:首先处理读取的网格str数组为g数组,若为地雷,则对应位置为-1,否则对应位置为以当前位置作为中心九宫格内地雷数量。然后遍历新数组g,若为0,则点击次数加一,再使用DFS处理当前位置即周围九宫格,若也为0继续DFS,所有搜索过的位置都标记为-1,最后再遍历一遍数组g,此时数组中应没有0,凡是不为-1的点击次数都加一。

import java.util.*;

public class Main {
    private static int T;
    private static int n;
    private static char[][] str;
    private static int[][] g;
    
    private static void dfs(int a, int b) {
        int t = g[a][b];
        g[a][b] = -1;
        if (t != 0) {
            return;
        }
        
        for (int x = a - 1; x <= a + 1; x++) {
            for (int y = b - 1; y <= b + 1; y++) {
                if (x >= 0 && x < n && y >= 0 && y < n && g[x][y] != -1) {
                    dfs(x, y);
                }
            }
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        T = sc.nextInt();
        
        for (int cases = 1; cases <= T; cases++) {
            n = sc.nextInt();
            str = new char[n][n];
            g = new int[n][n];
            sc.nextLine();
            for (int i = 0; i < n; i++) {
                String line = sc.nextLine();
                str[i] = line.toCharArray();
            }
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (str[i][j] == '*') {
                        g[i][j] = -1;
                    }
                    else {
                        g[i][j] = 0;
                        for (int x = i - 1; x <= i + 1; x++) {
                            for (int y = j - 1; y <= j + 1; y++) {
                                if (x >= 0 && x < n && y >= 0 && y < n && str[x][y] == '*') {
                                    g[i][j]++;
                                }
                            }
                        }
                    }
                }
            }
            
            int res = 0;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (g[i][j] == 0) {
                        res++;
                        dfs(i, j);
                    }
                }
            }
            
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (g[i][j] != -1) {
                        res++;
                    }
                }
            }
            
            System.out.println("Case #" + cases + ": " + res);
        }
    }
}
posted @   he0707  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
点击右上角即可分享
微信分享提示