你有一张某海域NxN像素的照片,"."表示海洋、"#"表示陆地,如下所示:
.......
.##....
.##....
....##.
..####.
...###.
.......
其中"上下左右"四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
.......
.......
.......
.......
....#..
.......
.......
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
输入格式
第一行包含一个整数N。 (1 <= N <= 1000)
以下N行N列代表一张海域照片。
照片保证第1行、第1列、第N行、第N列的像素都是海洋。
输出格式
一个整数表示答案。
样例输入
7
.......
.##....
.##....
....##.
..####.
...###.
.......
样例输出
1
#include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
typedef pair<int,int> PII;
#define x first
#define y second
const int N = 1009;
char a[N][N];
int sn[N][N];
int n;
int dx[4] = {-1,1,0,0},dy[4] = {0,0,-1,1};
int bfs(int x, int y)
{ queue<PII> s;
s.push({x,y});
sn[x][y] = 1;
int flag = 0;
while(s.size())
{ PII t = s.front();
s.pop();
int ans = 0;
for(int i = 0; i < 4; i ++)
{ int fx = t.x + dx[i];
int fy = t.y + dy[i];
if(fx < 0 || fx >= n || fy < 0 || fy >= n || a[fx][fy] == '.') continue;
ans++;
if(sn[fx][fy] != 1)
{
s.push({fx,fy});
sn[fx][fy] = 1;
}
if(ans == 4 && flag == 0)
{ flag = 1;
}
}
}
return flag;
}
int main()
{ cin >> n;
int sum = 0;
int ss=0;
for(int i = 0; i < n; i ++) cin >> a[i];
memset(sn,0,sizeof sn);//初始化
for(int i = 0; i < n; i ++)
for(int j = 0; j < n; j ++)
{
if(a[i][j] == '#' && !sn[i][j])
{ ss++;
sum += bfs(i,j);
}
}
cout << ss - sum << endl;
return 0;
}