2018年第九届蓝桥杯【C++省赛B组】H题
全球变暖
你有一张某海域NxN像素的照片,".“表示海洋、”#"表示陆地,如下所示:
…
.##…
.##…
…##.
…####.
…###.
…
其中"上下左右"四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
…
…
…
…
…#…
…
…
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
这道题应该算简单的bfs,两次bfs即可,一次标识出有多少岛屿同时标识出没有被淹没的点
第二次bfs是去重将同一座岛屿的没有被淹没的点统计为一次即可
我测试了两组数据没有什么大问题,有错误欢迎指正呀~方法比较直观。有好的方法欢迎评论区留言嘻嘻
代码下面附了两组测试数据~
#include <bits/stdc++.h>
#define mst(a, n) memset(a, n, sizeof(a))
using namespace std;
const int N = 1e3 + 10;
struct node
{
int x;
int y;
}a, now, s;
int sum;
int n;
int vis[N][N];
int v[N][N];
string str[N];
int dir[4][2] = { {1, 0}, {0, 1}, {-1, 0}, {0, -1} };
bool in(int x, int y)
{
if (x < 0 || y < 0 || x >= n || y >= n)
{
return false;
}
return true;
}
bool check(int x, int y)
{
for (int i = 0; i < 4; i++)
{
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if (in(xx, yy) && str[xx][yy] == '.')
{
return true;
}
}
return false;
}
void bfs1()
{
queue<node> q;
q.push(a);
while (!q.empty())
{
now = q.front();
q.pop();
if (check(now.x, now.y))
{
vis[now.x][now.y] = 1;
}
for (int i = 0; i < 4; i++)
{
s.x = now.x + dir[i][0];
s.y = now.y + dir[i][1];
if (in(s.x, s.y) && !vis[s.x][s.y] && str[s.x][s.y] == '#')
{
vis[s.x][s.y] = 2;
q.push(s);
}
}
}
sum++;
}
void bfs2()
{
queue<node> q;
q.push(a);
vis[a.x][a.y] = 3;
v[a.x][a.y] = 1;
while (!q.empty())
{
now = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
s.x = now.x + dir[i][0];
s.y = now.y + dir[i][1];
if (in(s.x, s.y) && str[s.x][s.y] == '#' && !v[s.x][s.y])
{
v[s.x][s.y] = 1;
if (vis[s.x][s.y] == 2)
{
vis[s.x][s.y] = 3;
}
q.push(s);
}
}
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> str[i];
}
sum = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (str[i][j] == '#' && !vis[i][j])
{
a.x = i;
a.y = j;
bfs1();
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (vis[i][j] == 2)
{
sum--;
a.x = i;
a.y = j;
bfs2();
}
}
}
cout << sum << endl;
return 0;
}
/*
7
.......
.#...#.
.#.###.
...###.
.#####.
...#...
.......
7
.......
.#...#.
.#.###.
...###.
.#####.
...#...
.......
*/