你有一张某海域NxN像素的照片,"."表示海洋、"#"表示陆地,如下所示:
....... .##.... .##.... ....##. ..####. ...###. .......
其中"上下左右"四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。
具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
....... ....... ....... ....... ....#.. ....... .......
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
输入
第一行包含一个整数N。 (1 <= N <= 1000)
以下N行N列代表一张海域照片。
照片保证第1行、第1列、第N行、第N列的像素都是海洋。
输出
一个整数表示答案。
样例输入 Copy
7 ....... .##.... .##.... ....##. ..####. ...###. .......
样例输出 Copy
1
#include <iostream>
#include <iterator>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
#include <list>
#include <set>
#include <map>
using namespace std;
typedef pair<int, int> PII;
int dis[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
char island[1001][1001];
bool vis[1001][1001];
int brink, total, n;
void BFS(int i, int j)
{
queue<PII> q;
q.push({i, j});
while(q.size())
{
PII start = q.front();
q.pop();
total ++;
bool is_brink = false;
for(int i = 0;i < 4;i ++ )
{
int x = start.first + dis[i][0];
int y = start.second + dis[i][1];
if(x < 0 || y < 0 || x >= n || y >= n || vis[x][y])
continue;
if(island[x][y] == '.')
{
is_brink = true;
continue;
}
q.push({x, y});
vis[x][y] = true;
}
if(is_brink)
brink ++;
}
}
int main()
{
int cnt = 0;
cin >> n;
for(int i = 0;i < n;i ++ )
{
cin >> island[i];
}
for(int i = 0;i < n;i ++ )
{
for(int j = 0;j < n;j ++ )
{
if(island[i][j] == '#' && !vis[i][j])
{
brink = 0;
total = 0;
BFS(i, j);
if(brink == total)
cnt ++;
}
}
}
cout << cnt << endl;
return 0;
}