题解 | 剪纸游戏
剪纸游戏
https://www.nowcoder.com/practice/33054daa2cc04fd6b97a0d18ccfc66a0
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <queue>
#include <climits>
using namespace std;
const int dx[4] = { 0, 0, 1, -1 };
const int dy[4] = { 1, -1, 0, 0 };
int n, m;
char arr[1005][1005];
bool visited[1005][1005];
int main() {
scanf("%d%d", &n, &m);
getchar(); // 读取换行
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf("%c", &arr[i][j]);
}
getchar(); // 读取每行末尾的换行
}
int ans = 0;
// 遍历所有格子
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
// 找到未访问的被剪去的格子,开始BFS
if (arr[i][j] == '.' && !visited[i][j]) {
queue<pair<int, int>> q;
q.push({ i, j });
visited[i][j] = true;
int cnt = 1;
int min_r = i, max_r = i;
int min_c = j, max_c = j;
// BFS遍历连通块
while (!q.empty()) {
auto cur = q.front();
q.pop();
int x = cur.first;
int y = cur.second;
// 更新连通块的边界
if (x < min_r) min_r = x;
if (x > max_r) max_r = x;
if (y < min_c) min_c = y;
if (y > max_c) max_c = y;
// 遍历四个方向
for (int k = 0; k < 4; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
// 边界检查 + 未访问 + 是被剪去的格子
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m
&& arr[nx][ny] == '.' && !visited[nx][ny]) {
visited[nx][ny] = true;
q.push({ nx, ny });
cnt++;
}
}
}
// 计算包围矩形的面积
int area = (max_r - min_r + 1) * (max_c - min_c + 1);
// 若实际格子数等于矩形面积,则为长方形
if (cnt == area) {
ans++;
}
}
}
}
printf("%d\n", ans);
return 0;
}
查看14道真题和解析