你有一张某海域NxN像素的照片,".“表示海洋、”#"表示陆地,如下所示:
.......
.##....
.##....
....##.
..####.
...###.
.......
其中"上下左右"四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像
素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
.......
.......
.......
.......
....#..
.......
.......
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
【输入格式】
第一行包含一个整数N。 (1 <= N <= 1000)
以下N行N列代表一张海域照片。
照片保证第1行、第1列、第N行、第N列的像素都是海洋。
【输出格式】
一个整数表示答案。
【输入样例】
7
…
.##…
.##…
…##.
…####.
…###.
…
【输出样例】
1
参考代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1001;
char a[maxn][maxn];
const int f[4] = {1,0,0,-1};
const int g[4] = {0,-1,1,0};
typedef pair<int,int>p;
void bfs(int x,int y)
{
queue<p>que;
que.push(p(x,y));
a[x][y] = '1';
while(!que.empty())
{
int m = que.front().first;
int n = que.front().second;
que.pop();
for(int i = 0; i < 4; i++)
{
int nx = m+f[i];
int ny = n+g[i];
if(a[nx][ny] == '#')
{
a[nx][ny] = '1'; //遍历过记为1
que.push(p(nx,ny));
}
}
}
}
void destory(int x,int y)
{
if(a[x-1][y] == '.' || a[x+1][y] == '.' || a[x][y+1] == '.' ||a[x][y-1] == '.')
{
a[x][y] = '0'; //被销毁记为0
}
}
int main()
{
int n;
cin>>n;
int cnt = 0,end = 0,result;
for(int i = 0; i < n; i++)
scanf("%s",a+i);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(a[i][j] == '#')
{
bfs(i,j);
cnt++; //找出原来岛的数量
}
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(a[i][j] == '1')
{
destory(i,j);//毁灭岛
}
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(a[i][j] == '1')
{
bfs(i,j);
end++; //找出剩下岛的数量
}
}
}
result = cnt-end; //原来岛的数量-剩下的 = 被销毁的
if(result > 0)
cout<<result<<endl;
else
cout<<"0"<<endl; //剩下的可能比原来多
return 0;
}