⭐ 原题地址
import java.io.*;
import java.util.*;
public class Main
{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
static int N = 1010, n;
static char[][] a = new char[N][N];
static boolean[][] st = new boolean[N][N];
static int[] dx = {
1, 0, -1, 0 };
static int[] dy = {
0, 1, 0, -1 };
public static void main(String[] args) throws IOException
{
n = Integer.parseInt(in.readLine());
for (int i = 1; i <= n; i++)
{
String s = in.readLine();
for (int j = 1; j <= n; j++)
a[i][j] = s.charAt(j - 1);
}
int cnt = 0;// 记录被淹没的岛屿数
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
if (!st[i][j] && a[i][j] == '#')
{
boolean b = bfs(i, j);
if (b)
cnt++;
}
}
System.out.println(cnt);
}
// 只要这个岛中有一点不会被淹没就返回 false
private static boolean bfs(int x, int y)
{
boolean res = true;// true 表示此岛会被淹没
st[x][y] = true;// 先标记已遍历
Node[] q = new Node[N * N];
int hh = 0;
int tt = -1;
q[++tt] = new Node(x, y);
while (hh <= tt)
{
Node t = q[hh++];
x = t.x;
y = t.y;
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (xx < 1 || xx > n || yy < 1 || yy > n || st[xx][yy])
continue;
// 该点不会被淹没
if (!check(xx, yy) && a[xx][yy] == '#')
{
res = false;
}
if (a[xx][yy] == '#')
{
q[++tt] = new Node(xx, yy);
st[xx][yy] = true;
}
}
}
return res;
}
// 检查该块岛屿是否会被淹没
private static boolean check(int x, int y)
{
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (a[xx][yy] == '.')
return true;
}
return false;
}
static class Node
{
int x;
int y;
public Node(int x, int y)
{
super();
this.x = x;
this.y = y;
}
}
}