题解 | 扫雷
扫雷
https://www.nowcoder.com/practice/d5f277427d9a4cd3ae60ea6c276dddfd
#include <iostream>
#include <vector>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
size_t n, m;
cin >> n >> m;
vector<string> vec(n);
for (int i = 0; i < n; ++i) {
cin >> vec[i];
}
// 定义八个方向
vector<pair<int, int>> dirs = {{-1, -1}, {-1, 0}, {-1, 1},
{0, -1}, {0, 1},
{1, -1}, {1, 0}, {1, 1}};
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (vec[i][j] == '*') {
cout << "*";
} else {
// 统计8领域雷数
int count = 0;
for (const auto &dir : dirs) {
int x = i + dir.first;
int y = j + dir.second;
// 边界判断:坐标个发且是雷
if (x >= 0 && x < n && y >= 0 && y < m && vec[x][y] == '*') {
count++;
}
}
// 输出雷数
cout << count;
}
}
cout << endl;
}
return 0;
}