acwing1233.全球变暖
算法:Flood Fill
bfs / dfs
统计被完全淹没的岛屿
两种方法:
1. 使用 total 和 bound 记录岛屿格子的数量和被淹没的格子数量,如果 bound == total,说明这个岛屿被完全淹没了。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
#define x first
#define y second
const int N = 1010;
int n;
bool st[N][N];
char s[N][N];
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
void bfs(PII start, int& total, int& bound) { //使用引用可以影响原变量
queue<PII> q;
q.push(start);
st[start.x][start.y] = true;
while (!q.empty())
{
PII t = q.front();
q.pop();
total ++ ;//每次有一个格子出栈总数量加一
bool is_bound = false;
for (int i = 0; i < 4; i++)
{
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 (s[x][y] == '.')
{
is_bound = true;//周围有海洋则标记当前格子
continue;
}
st[x][y] = true;
q.push({x, y});
}
if(is_bound) bound ++ ;//当前格子被标记了则bound++
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> s[i];
// 原始岛屿数量
int cnt = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
if (s[i][j] == '#' && !st[i][j])
{
int total = 0, bound = 0;
bfs({i, j}, total, bound);
if(total == bound) cnt ++ ;
}
}
cout << cnt << endl;
return 0;
}
2. 使用vector<vector<PII>> islands 记录岛屿数量 vector<PII>记录每个岛屿内部的格子 ,模拟一遍淹没的过程将岛屿变成海洋,如果一个岛屿内部所有的格子都别淹没了res ++ ;(学习vector的使用方法)
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
#define x first
#define y second
const int N = 1010;
int n;
bool st[N][N];
char g[N][N]; // 改用g存储原始地图
bool drown[N][N]; // 淹没标记数组
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
vector<vector<PII>> islands; // 存储所有原始岛屿
void bfs(PII start, vector<PII>& island) {
queue<PII> q;
q.push(start);
st[start.x][start.y] = true;
island.push_back(start);
while (!q.empty()) {
auto t = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int a = t.x + dx[i], b = t.y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= n) continue;
if (st[a][b] || g[a][b] != '#') continue;
st[a][b] = true;
q.push({a, b});
island.push_back({a, b});
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> g[i];
// BFS:记录所有原始岛屿
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (g[i][j] == '#' && !st[i][j]) {
vector<PII> island;
bfs({i, j}, island);
islands.push_back(island);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (g[i][j] != '#') continue;
for (int k = 0; k < 4; k++) {
int a = i + dx[k], b = j + dy[k];
if (a >= 0 && a < n && b >= 0 && b < n && g[a][b] == '.') {
drown[i][j] = true;
break;
}
}
}
}
// 统计完全被淹没的岛屿数量
int res = 0;
for (auto& island : islands) {
bool all_drowned = true;
for (auto& p : island) {
if (!drown[p.x][p.y]) { // 存在未被淹没的陆地
all_drowned = false;
break;
}
}
if (all_drowned) res++;
}
cout << res << endl;
return 0;
}