题解
2024-08-15 12:48:32
发布于:浙江
0阅读
0回复
0点赞
#include <iostream>
#include <vector>
// 检查坐标是否合法
bool is_valid(int x, int y, int n, int m) {
return x >= 0 && x < n && y >= 0 && y < m;
}
// 计算周围地雷数量
int count_mines(std::vector<std::vector<char>>& field, int x, int y) {
int count = 0;
int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};
int n = field.size();
int m = field[0].size();
for (int i = 0; i < 8; i++) {
int new_x = x + dx[i];
int new_y = y + dy[i];
if (is_valid(new_x, new_y, n, m) && field[new_x][new_y] == '*') {
count++;
}
}
return count;
}
int main() {
int n, m;
std::cin >> n >> m;
std::vector<std::vector<char>> field(n, std::vector<char>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
std::cin >> field[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (field[i][j] == '?') {
int num_mines = count_mines(field, i, j);
std::cout << num_mines;
} else {
std::cout << field[i][j];
}
}
std::cout << std::endl;
}
return 0;
}
这里空空如也
有帮助,赞一个