跳转链接
https://www.acwing.com/problem/content/1235/
来源:第九届蓝桥杯省赛C++A/B组,第九届蓝桥杯省赛JAVAA/B组
题目描述
你有一张某海域 N×N 像素的照片,”.”表示海洋、”#”表示陆地,如下所示:
…
.##…
.##…
…##.
…####.
…###.
…
其中”上下左右”四个方向上连在一起的一片陆地组成一座岛屿,例如上图就有 2 座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。
具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
…
…
…
…
…#…
…
…
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
输入格式
第一行包含一个整数N。
以下 N 行 N 列,包含一个由字符”#”和”.”构成的 N×N 字符矩阵,代表一张海域照片,
”#”表示陆地,”.”表示海洋。
照片保证第 1 行、第 1 列、第 N 行、第 N 列的像素都是海洋。
输出格式
一个整数表示答案。
数据范围
1
≤
N
≤
1000
1≤N≤1000
1≤N≤1000
输入样例1
7
.......
.##....
.##....
....##.
..####.
...###.
.......
输出样例1
1
输入样例2
9
.........
.##.##...
.#####...
.##.##...
.........
.##.#....
.#.###...
.#..#....
.........
输出样例2
1
题解思路
Flood Fill算法,用DFS、BFS皆可
只需要定义一个total统计一个连通块中的所有像素数量
再定义一个bound统计周围有海水的像素块的数量
如果最后total == bound说明会被淹没,cnt+1;
代码
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 1010;
int n;
bool st[N][N];
char g[N][N];
queue<PII>q;
int dx[] = {0,1,0,-1}, dy[] = {1,0,-1,0};
void bfs(int sx, int sy, int &total, int &bound) // 传引用是为了让局部变量接受值
{
q.push({sx, sy});
st[sx][sy] = true;
while (q.size())
{
auto t = q.front();
q.pop(); // 记得一定要将队头像素弹出队列
total++;
bool is_bound = false; // 先假设周围没有海水
for (int i = 0; i < 4; i++) // 向4个方向扫描像素
{
int x = t.x + dx[i], y = t.y + dy[i];
if (x < 0 || x >= n || y < 0 || y >= n) continue;
if (st[x][y]) continue;
if (g[x][y] == '.') // 周围扫到的像素是海水,说明像素t周围有海水
{
is_bound = true;
continue;
}
q.push({x, y}); // 经过上面的条件筛选后,一定是像素,加入队列
st[x][y] = true; // 标记为已经扫描过
}
if(is_bound) bound++;
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++) cin >> g[i];
int cnt = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (!st[i][j] && g[i][j] == '#')
{
/*total统计一个连通块中的所有像素数量
bound统计周围有海水的像素块的数量*/
int total = 0, bound = 0;
bfs(i, j, total, bound);
if (total == bound) cnt++;
}
cout << cnt;
return 0;
}