题目:
https://www.luogu.com.cn/problem/P1162
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int board[30][30];
int vis[30][30];
typedef struct qunre
{
int x, y;
//入果加一个s[1000]; 表示路程,就可以记录最小路程
} qunre;
int n;
qunre q[900];
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
void bfs(int x, int y)
{
int t = 0, h = 0;//这边比较的特殊,每次用DFS其实h和t都是要初始化的
if (vis[x][y] || board[x][y])
return;
vis[x][y] = 1;
q[t++] = {x, y};
while (h != t)
{
auto [ux, uy] = q[h++];
for (int i = 0; i < 4; i++)
{
int tx, ty;
tx = ux + dx[i];
ty = uy + dy[i];
if (tx >= 0 && tx < n && ty >= 0 && ty < n && !vis[tx][ty] && !board[tx][ty])
{
vis[tx][ty] = 1;
q[t++] = {tx, ty};
}
}
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%d", &board[i][j]);
}
}
for (int i = 0; i < n; i++)
{
bfs(0, i);
bfs(i, 0);
bfs(i, n - 1);
bfs(n - 1, i);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
printf("%d ", vis[i][j] ? 0 : (board[i][j] ? 1 : 2));
}
printf("\n");
}
system("pause");
return 0;
}