思路:
Flood fill算法,可以用dfs或者bfs来做,由题意得,通过遍历连通的陆地,确定为一个岛屿,如果一个岛屿中的每个陆地都靠近海洋,则全部淹没,如果不是,则该岛屿没有被完全淹没
代码:
# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;
# define x first
# define y second
typedef pair<int ,int> PII;
const int N = 1010;
char g[N][N];
bool st[N][N];
int n;
PII q[N * N];
int dx[4] = {
0,1,0,-1};
int dy[4] = {
1,0,-1,0};
void bfs(int sx,int sy,int &total,int &bound)
{
int tt = 0,hh = 0;
q[0] = {
sx,sy};
st[sx][sy] = true;
while(hh <= tt)
{
PII t = q[hh++];
total++;
bool is_bound = false;//判断陆地是否会被淹没
for(int i = 0;i < 4;i++)
{
int x = t.x + dx[i],y = t.y + dy[i];
if(x < 0 || x >= n || y < 0 || y >= n) continue;
if(st[x][y]) continue;
if(g[x][y] == '.')
{
is_bound = true;
continue;
}
q[++tt] = {
x,y};
st[x][y] = true;
}
if(is_bound)
bound++;
}
}
int main()
{
scanf("%d",&n);
for(int i = 0;i < n;i++)
{
scanf("%s",g[i]);
}
int cnt = 0;
for(int i = 0;i < n;i++)
{
for(int j = 0;j < n;j++)
{
if(!st[i][j] && g[i][j] == '#')
{
int total = 0,bound = 0;//total当前位置连通陆地的数量,bound表示被淹没陆地的数量
bfs(i,j,total,bound);
if(total == bound)//完整淹没的岛屿
{
cnt++;
}
}
}
}
printf("%d\n",cnt);
return 0;
}