十四 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 @ 2024-03-26 15:09  he0707  阅读(14)  评论(0)    收藏  举报