AcWing 1233. 全球变暖(bfs)

Problem

这个题依旧是一个bfs问题,做法是类似并查集那样,找到一个#就去搜索和这个#相连的所有#

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Queue;

class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int N = 1010, n;
    static char g[][] = new char[N][N];
    static boolean st[][] = new boolean[N][N];
    static int dx[] = new int[]{0, 0, 1, -1};
    static int dy[] = new int[]{1, -1, 0, 0};

    public static void main(String args[]) throws IOException {
        n = Integer.parseInt(br.readLine());
        for (int i = 0; i < n; i++) {
            String s = br.readLine();
            for (int j = 0; j < n; j++)
                g[i][j] = s.charAt(j);
        }

        int res = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (!st[i][j] && g[i][j] == '#') {
                    if (bfs(i, j))
                        res++;
                }
            }
        }
        pw.print(res);
        pw.flush();
        pw.close();
        br.close();

    }

    public static boolean bfs(int i, int j) {
        Queue<Pair> q = new ArrayDeque<>();
        q.offer(new Pair(i, j));
        st[i][j] = true;
        int total = 0, bound = 0;
        while (!q.isEmpty()) {
            Pair temp = q.poll();
            total++;
            st[temp.x][temp.y] = true;
            boolean on_bound = false;
            for (int k = 0; k < 4; k++) {
                int x = temp.x + dx[k];
                int y = temp.y + dy[k];
                if (x < 0 || x >= n || y < 0 || y >= n) continue;
                if (st[x][y]) continue;
                if (g[x][y] == '.') {
                    on_bound = true;
                    continue;
                }
                q.offer(new Pair(x, y));
                st[x][y] = true;
            }
            if (on_bound) bound++;
        }
        return total == bound;
    }

}

class Pair {
    int x, y;

    public Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
发布了167 篇原创文章 · 获赞 3 · 访问量 3401

猜你喜欢

转载自blog.csdn.net/qq_43515011/article/details/104576011
今日推荐