跳到正文

题解

题解:P16486 [GKS 2014 #C] Minesweeper

liu_yu_xiang约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年5月18日
收录
2026年5月21日
更新
2026年10月9日
篇幅
约 4 分钟
题目
P16486

版本

  1. v1当前

本篇题解使用 DFS 解题

思路:累加连通块(指 00 的连通块和 00 的相邻格)的个数,以及与 00 不相邻的非地雷格子。

预处理分析:如果当前格是地雷,数组值是 −1-1;否则当前格八个方向的地雷数就是数组的值。

复杂度:预处理 O(N2)O(N^2),DFS 搜索 O(N2)O(N^2),总复杂度 O(N2)O(N^2),空间复杂度 O(N2)O(N^2)。

如还有不懂处详见注释。

代码部分

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
int T, N;
char mp[305][305];
int vis[305][305];
int cnt[305][305];
int dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};
int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
void init() { // 预处理,将数据填充至 cnt 数组
	for (int i = 1; i <= N; i++) {
		for (int j = 1; j <= N; j++) {
			if (mp[i][j] == '*') {
				cnt[i][j] = -1;
				continue;
			}
			int num = 0;
			for (int k = 0; k < 8; k++) {
				int nx = i + dx[k];
				int ny = j + dy[k];
				if (nx >= 1 && nx <= N && ny >= 1 && ny <= N && mp[nx][ny] == '*')
					num++;
			}
			cnt[i][j] = num;
		}
	}
}
void dfs(int x, int y) {
	vis[x][y] = 1; // 打标
	for (int i = 0; i < 8; i++) {
		int nx = x + dx[i];
		int ny = y + dy[i];
		if (nx >= 1 && nx <= N && ny >= 1 && ny <= N && !vis[nx][ny] && cnt[nx][ny] != -1) {
			if (cnt[nx][ny] == 0)
				dfs(nx, ny); // 搜索0的连通块
			else
				vis[nx][ny] = 1; // 继续打标,退出递归
		}
	}
}
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	cin >> T;
	for (int t = 1; t <= T; t++) {
		cin >> N;
		for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				cin >> mp[i][j];
			}
		}
		init();
		memset(vis, 0, sizeof(vis)); // 多测不清空,爆零两行泪
		int ans = 0;
		for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				if (!vis[i][j] && cnt[i][j] == 0) {
					dfs(i, j);
					ans++;
				}
			}
		} // 搜索0的连通块和相邻非零格
		for (int i = 1; i <= N; i++) {
			for (int j = 1; j <= N; j++) {
				if (!vis[i][j] && cnt[i][j] != -1)
					ans++;
			}
		} // 累加与0不相邻的格子
		cout << "Case #" << t << ": " << ans << "\n"; // 按要求输出
	}
	return 0; // 完结散花
}

AC记录

原文
存档评论3 条抓取于