加我团队了吗,孩子?
2026-03-19 22:05:24
发布于:江苏
3阅读
0回复
0点赞
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 方向数组:8个可能的相邻位置
const int directions[8][2] = {
{-1, -1}, {-1, 0}, {-1, 1},
{0, -1}, {0, 1},
{1, -1}, {1, 0}, {1, 1}
};
// 计算单个格子周围的地雷数量
int countAdjacentMines(const vector<string>& grid, int row, int col, int n, int m) {
int count = 0;
// 检查8个方向
for (const auto& dir : directions) {
int newRow = row + dir[0];
int newCol = col + dir[1];
// 边界检查和地雷检查合并为一行,减少分支
if (newRow >= 0 && newRow < n && newCol >= 0 && newCol < m && grid[newRow][newCol] == '*') {
count++;
}
}
return count;
}
// 处理整个雷区并生成结果
vector<string> processMinefield(const vector<string>& grid, int n, int m) {
vector<string> result(n, string(m, '0'));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == '*') {
result[i][j] = '*'; // 保留地雷
} else {
// 计算并转换为字符
result[i][j] = '0' + countAdjacentMines(grid, i, j, n, m);
}
}
}
return result;
}
// 输出雷区结果
void printMinefield(const vector<string>& field) {
for (const string& row : field) {
cout << row << endl;
}
}
int main() {
ios::sync_with_stdio(false); // 加快输入输出速度
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<string> grid(n);
for (int i = 0; i < n; ++i) {
cin >> grid[i];
}
vector<string> result = processMinefield(grid, n, m);
printMinefield(result);
return 0;
}
这里空空如也




有帮助,赞一个