题目链接:https://www.acwing.com/problem/content/description/1235/
你有一张某海域 N×NN×N 像素的照片,”.”表示海洋、”#”表示陆地,如下所示:
.......
.##....
.##....
....##.
..####.
...###.
.......
其中”上下左右”四个方向上连在一起的一片陆地组成一座岛屿,例如上图就有 22 座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。
具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
.......
.......
.......
.......
....#..
.......
.......
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
输入格式
第一行包含一个整数N。
以下 NN 行 NN 列,包含一个由字符”#”和”.”构成的 N×NN×N 字符矩阵,代表一张海域照片,”#”表示陆地,”.”表示海洋。
照片保证第 11 行、第 11 列、第 NN 行、第 NN 列的像素都是海洋。
扫描二维码关注公众号,回复:
9193635 查看本文章
输出格式
一个整数表示答案。
数据范围
1≤N≤10001≤N≤1000
输入样例1:
7
.......
.##....
.##....
....##.
..####.
...###.
.......
输出样例1:
1
输入样例2:
9
.........
.##.##...
.#####...
.##.##...
.........
.##.#....
.#.###...
.#..#....
.........
输出样例2:
1
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
queue<pii> q;
const int N=1010;
const int dx[]={0,0,-1,1};
const int dy[]={1,-1,0,0};
int n,res;
char ch[N][N];
bool pd[N][N];
int bfs(){
int cnt=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(!pd[i][j]&&ch[i][j]=='#'){
cnt++;
q.push({i,j});
bool judge=false;
while(q.size()){
auto t = q.front();
q.pop();
for(int k=0;k<4;k++){
int a=t.first+dx[k],b=t.second+dy[k];
if(!pd[a][b]&&a>0&&b>0&&a<=n&&b<=n&&ch[a][b]=='#'){
q.push({a,b});
bool flag=false;
pd[a][b]=true;
for(int w=0;w<4;w++){
int c=a+dx[w],d=b+dy[w];
if(ch[c][d]=='.'){
flag=true;
break;
}
}
if(!flag&&!judge){
res++;
judge=true;
}
}
}
}
}
}
}
return cnt;
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>ch[i][j];
}
}
printf("%d",bfs()-res);
return 0;
}