目录
1.题目
## 题目描述
你有一张某海域 $N \times N$ 像素的照片,`.` 表示海洋、 `#` 表示陆地,如下所示:
.......
.##....
.##....
....##.
..####.
...###.
.......
其中 "上下左右" 四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有 $2$ 座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
.......
.......
.......
.......
....#..
.......
.......
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
## 输入格式
第一行包含一个整数 $N$。$(1 \le N \le 1000)$。
以下 $N$ 行 $N$ 列代表一张海域照片。
照片保证第 $1$ 行、第 $1$ 列、第 $N$ 行、第 $N$ 列的像素都是海洋。
## 输出格式
一个整数表示答案。
## 样例 #1
### 样例输入 #1
7
.......
.##....
.##....
....##.
..####.
...###.
.......
### 样例输出 #1
1
## 提示
时限 1 秒, 256M。蓝桥杯 2018 年第九届省赛
2.AC
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int n, sum, flag;
int v[1010][1010], f[1010][1010];
int dx[4]={0,0,-1,1},dy[4]={1,-1,0,0};
char a[1010][1010];
struct node{
int x, y;
}p, t;
queue<node> q;
void bfs1(int u1, int u2) {
p.x = u1, p.y = u2;
v[u1][u2] = 1;
q.push(p);
while (!q.empty()) {
t = q.front(), q.pop();
for (int i = 0; i < 4; i++) {
int cx = t.x + dx[i];
int cy = t.y + dy[i];
if (cx<0 || cy<0 || cx>=n || cy>=n) continue;
if (!v[cx][cy]) {
if (a[cx][cy]=='.') {
f[t.x][t.y] = 1;
} else {
p.x = cx, p.y = cy;
q.push(p);
v[cx][cy] = 1;
}
}
}
}
}
void bfs2(int u1, int u2) {
p.x = u1, p.y = u2;
v[u1][u2] = 1;
q.push(p);
while (!q.empty()) {
t = q.front(), q.pop();
for (int i = 0; i < 4; i++) {
int cx = t.x + dx[i];
int cy = t.y + dy[i];
if (cx<0 || cy<0 || cx>=n || cy>=n) continue;
if (!v[cx][cy]&&a[cx][cy]=='#') {
if(!f[cx][cy]) flag = 1;
p.x = cx, p.y = cy;
q.push(p);
v[cx][cy] = 1;
}
}
}
}
int main () {
memset(v,0,sizeof(v));
memset(f,0,sizeof(f));
cin>>n;
for (int i = 0; i < n; i++) {
cin>>a[i];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j]=='#'&&!v[i][j]) {
bfs1(i,j);
sum++;
}
}
}
memset(v,0,sizeof(v));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
flag = 0;
if (a[i][j]=='#'&&!v[i][j]) {
bfs2(i,j);
if (flag) {
sum--;
}
}
}
}
cout<<sum;
return 0;
}