MSIPO技术圈 首页 IT技术 查看内容

蓝桥杯每日一题:扫雷

2024-03-25

题目来源:第十三届蓝桥杯软件赛省赛 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 1n,m100

输出 : 输出 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;
}

相关阅读

热门文章

    手机版|MSIPO技术圈 皖ICP备19022944号-2

    Copyright © 2024, msipo.com

    返回顶部