L2-4 寻宝图
给定一幅地图,其中有水域,有陆地。被水域完全环绕的陆地是岛屿。有些岛屿上埋藏有宝藏,这些有宝藏的点也被标记出来了。本题就请你统计一下,给定的地图上一共有多少岛屿,其中有多少是有宝藏的岛屿。
输入格式:
输入第一行给出 2 个正整数 N 和 M(1<N×M≤105),是地图的尺寸,表示地图由 N 行 M 列格子构成。随后 N 行,每行给出 M 位个位数,其中 0
表示水域,1
表示陆地,2
-9
表示宝藏。
注意:两个格子共享一条边时,才是“相邻”的。宝藏都埋在陆地上。默认地图外围全是水域。
输出格式:
在一行中输出 2 个整数,分别是岛屿的总数量和有宝藏的岛屿的数量。
输入样例:
10 11
01000000151
11000000111
00110000811
00110100010
00000000000
00000111000
00114111000
00110010000
00019000010
00120000001
输出样例:
7 2
#include <bits/stdc++.h>
using namespace std;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
void bfs(int x, int y, vector<vector<char>>& grid, bool& hasTreasure) {
int n = grid.size();
int m = grid[0].size();
queue<pair<int, int>> q;
q.push({x, y});
// 标记当前格子为已访问
grid[x][y] = '0';
while (!q.empty()) {
auto [cx, cy] = q.front();
q.pop();
// 检查当前格子是否是宝藏
if (grid[cx][cy] >= '2' && grid[cx][cy] <= '9') {
hasTreasure = true;
}
// 遍历四个方向
for (int i = 0; i < 4; i++) {
int nx = cx + dx[i];
int ny = cy + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] != '0') {
grid[nx][ny] = '0'; // 标记为已访问
q.push({nx, ny});
}
}
}
}
void solve() {
int n, m;
cin >> n >> m;
vector<vector<char>> grid(n, vector<char>(m));
// 读取地图
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> grid[i][j];
}
}
int totalIslands = 0;
int treasureIslands = 0;
// 遍历地图
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] != '0') {
bool hasTreasure = false;
bfs(i, j, grid, hasTreasure);
totalIslands++;
if (hasTreasure) {
treasureIslands++;
}
}
}
}
// 输出结果
cout << totalIslands << " " << treasureIslands << endl;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
solve();
return 0;
}
#include <bits/stdc++.h>
using namespace std;
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
void dfs(int x, int y, vector<vector<char>>& grid, bool& hasTreasure) {
int n = grid.size();
int m = grid[0].size();
if (grid[x][y] >= '2' && grid[x][y] <= '9') {
hasTreasure = true;
}
grid[x][y] = '0';
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] != '0') {
dfs(nx, ny, grid, hasTreasure);
}
}
}
void solve() {
int n, m;
cin >> n >> m;
vector<vector<char>> grid(n, vector<char>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> grid[i][j];
}
}
int totalIslands = 0;
int treasureIslands = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] != '0') {
bool hasTreasure = false;
dfs(i, j, grid, hasTreasure);
totalIslands++;
if (hasTreasure) {
treasureIslands++;
}
}
}
}
cout << totalIslands << " " << treasureIslands << endl;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
solve();
return 0;
}