1365: [蓝桥杯2018初赛]全球变暖
时间限制: 1 Sec 内存限制: 256 MB
提交: 652 解决: 108
[状态] [提交] [命题人:外部导入]
题目描述
你有一张某海域NxN像素的照片,".“表示海洋、”#"表示陆地,如下所示:
.......
.##....
.##....
....##.
..####.
...###.
.......
其中"上下左右"四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。
具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
.......
.......
.......
.......
....#..
.......
.......
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
输入
第一行包含一个整数N。 (1 <= N <= 1000)
以下N行N列代表一张海域照片。
照片保证第1行、第1列、第N行、第N列的像素都是海洋。
输出
一个整数表示答案。
样例输入 Copy
7
.......
.##....
.##....
....##.
..####.
...###.
.......
样例输出 Copy
1
AC代码:
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
using namespace std;
int N;//规模大小
int ans = 0;//最终结果(被淹没的岛屿数量)
//转向数组(上,下,左,右)
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,-1,1 };
class Point {
public:
int x, y;//坐标
Point(int xx, int yy) :x(xx), y(yy) {}
};
//判断访问是否会越界
bool outBorder(int x, int y) {
if (x < 0 || y < 0 || x >= N || y >= N) return true;
else return false;
}
void bfs(vector<vector<char>>& map, vector<vector<int>>& mark, int i, int j) {
mark[i][j] = 1;
queue<Point> q;
q.push(Point(i, j));
int cnt1 = 0, cnt2 = 0;//记录#的数量,和会被淹没的数量(即四周有.的#的数量)
while (!q.empty()) {
Point p = q.front();
q.pop();
cnt1++;
bool swed = false;//弹出的点是否会被淹没
//访问弹出的点的四个方向
for (int k = 0; k < 4; k++){
int x = p.x + dx[k];
int y = p.y + dy[k];
if (!outBorder(x, y) && map[x][y] == '.') swed = true;
if (!outBorder(x, y) && map[x][y] == '#' && mark[x][y] == 0) {
mark[x][y] = 1;//标记被访问
q.push(Point(x, y));//加入队列
}
}
if (swed) {
cnt2++;
}
}
if (cnt1 == cnt2)ans++;
}
int main() {
std::ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
N = n;
string str;
vector<vector<char>> graph;//地图
vector<vector<int>> vis(n, vector<int>(n, 0));//标记每个点是否被访问
for (int i = 0; i < n; i++) {
cin >> str;
graph.push_back(vector<char>(str.c_str(), str.c_str() + str.length()));
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
//遍历每一个没有被访问的岛屿
if (graph[i][j] == '#' && vis[i][j] == 0) {
bfs(graph, vis, i, j);
}
}
}
cout << ans << endl;
return 0;
}