// #pragma GCC optimize(2)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#include <bitset>
#define IO \
ios::sync_with_stdio(false); \
// cout.tie(0);
using namespace std;
// int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
typedef unsigned long long ULL;
typedef long long LL;
typedef pair<int, int> P;
const int maxn = 1e3 + 10;
const int maxm = 2e5 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
const double pi = acos(-1);
int dis[4][2] = {1, 0, 0, -1, 0, 1, -1, 0};
int m[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
char a[maxn][maxn];
bool vis[maxn][maxn];
int n;
bool judge(int x, int y)
{
if (x >= 1 && x <= n && y >= 1 && y <= n)
return true;
return false;
}
bool check(int x, int y)
{
if (judge(x - 1, y))
{
if (a[x - 1][y] == '.')
return true;
}
if (judge(x + 1, y))
{
if (a[x + 1][y] == '.')
return true;
}
if (judge(x, y + 1))
{
if (a[x][y + 1] == '.')
return true;
}
if (judge(x, y - 1))
{
if (a[x][y - 1] == '.')
return true;
}
return false;
}
bool BFS(int x, int y)
{
int all = 0;
int cnt = 0;
queue<pair<int, int>> q;
vis[x][y] = true;
q.push(make_pair(x, y));
while (!q.empty())
{
pair<int, int> p;
p = q.front();
q.pop();
all++;
int x = p.first;
int y = p.second;
if (check(x, y)==true)
cnt++;
for (int i = 0; i < 4; i++)
{
int tx = x + dis[i][0];
int ty = y + dis[i][1];
if (a[tx][ty] == '#' && vis[tx][ty] == false && judge(tx, ty))
{
vis[tx][ty] = true;
q.push(make_pair(tx, ty));
}
}
}
return cnt == all;
}
int main()
{
#ifdef WXY
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
IO;
cin >> n;
int cnt1 = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> a[i][j];
}
}
check(5, 5);
int cnt = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (vis[i][j] == false && a[i][j] == '#')
{
if (BFS(i, j))
cnt++;
}
}
}
cout << cnt;
return 0;
}
只需要判断当前连通块(#)中的#会不会被全部淹没,全部淹没,那么岛屿消失,否则不消失。