瀘州百度做網站聯系企業(yè)營銷模式
題目來源:第十三屆藍橋杯軟件賽省賽 B組
在一個 n n n 行 m m m 列 的方格圖中有些位置有地雷, 另外一些位置為空
請為每個空位置標一個整數, 表示周圍八個相鄰的方格中有多少個地雷
輸入 : 輸入的第一行包含兩個整數 n n n , m m m
第 2 行 到 第 n + 1 n + 1 n+1 行每行包含 m m m 個整數, 相鄰整數之間用一個空格分隔. 如果對應的整數為 0 , 表示這一格沒有地雷, 如果對應的整數為 1 , 表示這一格有地雷
其中, 1 ≤ n , m ≤ 100 1 \le n, m \le 100 1≤n,m≤100
輸出 : 輸出 n n n 行, 每行 m m m 個整數, 相鄰整數之間用空格分隔
對于沒有地雷的方格, 輸出這格周圍的地雷數量. 對于有地雷的方格, 輸出 9
Input Sample :
3 4 0 1 0 0 1 0 1 0 0 0 1 0
Output Sample :
2 9 2 1 9 4 9 2 1 3 9 2
簡單的爆搜題, 非常簡單, 而且其實這道題就是爆搜的模板題. 有系統練習過的話直接秒ac
藍橋杯居然還把它的難度評為 “困難” , 有點搞笑了
下面給出題解代碼, 請注重思考, 不要無腦cv
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int n, m;
const int maxn = 101;
int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
int a[maxn][maxn], res[maxn][maxn];void io() {cin.tie(0);cout.tie(0);ios::sync_with_stdio(false);
}int dfs(int x, int y) {if (a[x][y] == 1) {return 9;}int cnt = 0;for (int i = 0; i < 8; i++) {int xx = x + dx[i];int yy = y + dy[i];if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && a[xx][yy] == 1) {cnt++;}}return cnt;
}int main() {io();cin >> n >> m;for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {cin >> a[i][j];}}for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {res[i][j] = dfs(i, j);}}for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {cout << res[i][j] << ' ';}cout << '\n';}return 0;
}