0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 0 0 1
1 1 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1
0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 2 1
1 1 2 2 2 1
1 2 2 2 2 1
1 1 1 1 1 1
6 0 0 0 0 0 0 0 0 1 1 1 1 0 1 1 0 0 1 1 1 0 0 0 1 1 0 0 0 0 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1 0 1 1 2 2 1 1 1 2 2 2 1 1 2 2 2 2 1 1 1 1 1 1 1
#include <iostream> #include <stdio.h> #include <algorithm> #include <queue> using namespace std; int m[100][100]; int dir[][2] = { {1,0},{0,1},{-1,0},{0,-1} }; int n; struct node { int x, y; node(int a, int b) { x = a; y = b; } }; bool check(int a, int b) { if (a > n || a < 0 || b > n || b < 0) return false; return true; } void bfs() { queue<node> q; for (int i = 0; i < n; i++) { if (m[i][0] == 0) q.push(node(i, 0)); if (m[0][i] == 0) q.push(node(0, i)); if (m[i][n-1] == 0) q.push(node(i, n-1)); if (m[n-1][i] == 0) q.push(node(n-1, i)); } while (!q.empty()) { node t = q.front(); q.pop(); m[t.x][t.y] = 2; for (int i = 0; i < 4; i++) { int xx = t.x + dir[i][0]; int yy = t.y + dir[i][1]; if(m[xx][yy] == 0 && check(xx, yy)) q.push(node(xx, yy)); } } } int main(){ scanf("%d", &n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { scanf("%d", &m[i][j]); } } bfs(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (m[i][j] == 2) cout << 0 << " "; else if (m[i][j] == 0) cout << 2 << " "; else cout << 1 << " "; } cout << endl; } return 0; }
原文:https://www.cnblogs.com/woxiaosade/p/10635784.html