P1162(BFS)
Posted huluxin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了P1162(BFS)相关的知识,希望对你有一定的参考价值。
1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 #include <cstring> 5 #include <algorithm> 6 #include <queue> 7 using namespace std; 8 struct node 9 { 10 int x, y; 11 }; 12 int a[35][35], n, vis[35][35]; 13 int dir[4][2] = { -1,0,1,0,0,-1,0,1 }; 14 void bfs(int sx,int sy) 15 { 16 node s,temp,next; 17 s.x = sx; 18 s.y = sy; 19 queue<node>q; 20 q.push(s); 21 while (!q.empty()) 22 { 23 temp = q.front(); q.pop(); 24 for (int i = 0; i < n; i++) 25 { 26 next.x = temp.x + dir[i][0]; 27 next.y = temp.y + dir[i][1]; 28 if (next.x >= 0 && next.x < n&&next.y >= 0 && next.y < n&&vis[next.x][next.y]==0&&a[next.x][next.y]==0) 29 { 30 vis[next.x][next.y] = 1; 31 q.push(next); 32 } 33 } 34 } 35 } 36 int main() 37 { 38 39 while (cin >> n) 40 { 41 for (int i = 0; i < n; i++) 42 for (int j = 0; j < n; j++) 43 cin >> a[i][j]; 44 memset(vis, 0, sizeof(vis)); 45 for (int i = 0; i < n; i++) 46 { 47 if (vis[i][0] == 0&& a[i][0] == 0) 48 { 49 vis[i][0] = 1; 50 bfs(i, 0); 51 } 52 } 53 for (int i = 0; i < n; i++) 54 { 55 if (vis[0][i] == 0&& a[0][i] == 0) 56 { 57 vis[0][i] = 1; 58 bfs(0, i); 59 } 60 } 61 for (int i = 0; i < n; i++) 62 { 63 if (vis[i][n-1] == 0&&a[i][n - 1] == 0) 64 { 65 vis[i][n-1] = 1; 66 bfs(i, n-1); 67 } 68 } 69 for (int i = 0; i < n; i++) 70 { 71 if (vis[n-1][i] == 0&& a[n - 1][i] == 0) 72 { 73 vis[n-1][i] = 1; 74 bfs(n-1, i); 75 } 76 } 77 for (int i = 0; i < n; i++) 78 { 79 for (int j = 0; j < n; j++) 80 { 81 if (vis[i][j]) 82 cout << "0"; 83 else if (a[i][j]) 84 cout << a[i][j]; 85 else 86 cout << "2" ; 87 if (j != n - 1) 88 cout << " "; 89 } 90 cout << endl; 91 } 92 } 93 return 0; 94 }
以上是关于P1162(BFS)的主要内容,如果未能解决你的问题,请参考以下文章