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;
}