Skip to content
Author: loop3r
Date: 20260223
tag: 模拟
link: https://www.luogu.com.cn/problem/P2670

问题描述

link

分析

按题意模拟,可以使用数组存储八个方向的坐标偏移量,遍历每个格子,如果是雷则输出 *,否则统计周围八个格子中雷的数量并输出。

参考代码

cpp
#include <bits/stdc++.h>
using namespace std;

char g[105][105];
int n, m;
int dx[] = {-1, -1, -1, 0, 1, 1, 1, 0};
int dy[] = {-1, 0, 1, 1, 1, 0, -1, -1};

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; i++) cin >> g[i];

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (g[i][j] == '*') {
                cout << g[i][j];
                continue;
            }
            int cnt = 0;
            for (int k = 0; k < 8; k++) {
                int nx = i + dx[k], ny = j + dy[k];
                if (nx < 0 || nx >= n) continue;
                if (ny < 0 || ny >= m) continue;

                if (g[nx][ny] == '*') cnt++;
            }
            cout << cnt;
        }
        cout << endl;
    }

    return 0;
}