1. 程式人生 > 實用技巧 >Find a way(BFS)

Find a way(BFS)

原題連結

這道題做了改了一整天,到現在終於算是做對了。。。

不解的是同時對兩個佇列進行操作的時候位於後面的一個

佇列會出現只能走一兩步的情況,在這卡了好久也沒想明白

是怎麼回事,於是換了個思路,將兩個人走的路線分別求出來,

最後遍歷一下找出符合條件的最小值就行了。

需要兩個布林陣列用來判斷兩個人在地圖中哪些點走過了,

還有兩個計數陣列(一個也行, 兩個更直觀),也就是兩個人

都遍歷一下,然後求最小值(到達KFC的最小值)。

 1 #include <iostream>
 2 #include <cstring>
 3 #include <queue>
 4
#include <algorithm> 5 using namespace std; 6 const int N = 210; 7 int n, M; 8 bool vism[N][N], visy[N][N]; 9 char maze[N][N]; 10 int cntm[N][N], cnty[N][N]; 11 struct nodem{ 12 int x, y, d; 13 nodem(int xx, int yy, int dd){ 14 x = xx, y = yy, d = dd; 15 } 16 }; 17 struct
nodey{ 18 int x, y, d; 19 nodey(int xx, int yy, int dd){ 20 x = xx, y = yy, d = dd; 21 } 22 }; 23 int dir[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; 24 queue<nodem> m; 25 queue<nodey> y; 26 int bfs(int mx, int my, int yx, int yy){ 27 m.push(nodem(mx, my, 0)); 28 y.push(nodey(yx, yy, 0
)); 29 vism[mx][my] = true; 30 visy[yx][yy] = true; 31 while(!m.empty()) { 32 nodem nowm = m.front(); 33 m.pop(); 34 vism[nowm.x][nowm.y] = true; 35 for(int i = 0; i < 4; i ++){ 36 int tx = nowm.x + dir[i][0], ty = nowm.y + dir[i][1]; 37 if(tx >= 0 && tx < n && ty >= 0 && ty < M && !vism[tx][ty] && maze[tx][ty] != '#'){ 38 m.push(nodem(tx, ty, nowm.d + 11)); 39 cntm[tx][ty] = nowm.d + 11; 40 vism[tx][ty] = true; 41 } 42 } 43 } 44 while(!y.empty()){ 45 nodey nowy = y.front(); 46 y.pop(); 47 visy[nowy.x][nowy.y] = true; 48 for(int i = 0; i < 4; i ++){ 49 int tx = nowy.x + dir[i][0], ty = nowy.y + dir[i][1]; 50 if(tx >= 0 && tx < n && ty >= 0 && ty < M && !visy[tx][ty] && maze[tx][ty] != '#'){ 51 y.push(nodey(tx, ty, nowy.d + 11)); 52 cnty[tx][ty] = nowy.d + 11; 53 visy[tx][ty] = true; 54 } 55 } 56 } 57 int minn = 0x3f3f3f; 58 for(int i = 0; i < n; i ++){ 59 for(int j = 0; j < M; j ++){ 60 if(vism[i][j] && visy[i][j] && maze[i][j] == '@'){ 61 minn = min(minn, cntm[i][j] + cnty[i][j]); 62 } 63 64 } 65 } 66 return minn; 67 } 68 int main(){ 69 while(cin >> n >> M){ 70 memset(vism, 0, sizeof vism); 71 memset(visy, 0, sizeof visy); 72 for(int i = 0; i < n; i ++) 73 cin >> maze[i]; 74 int yx, yy, mx, my; 75 for(int i = 0; i < n; i ++) 76 for(int j = 0; j < M; j ++) 77 if(maze[i][j] == 'Y') 78 yx = i, yy = j; 79 else if(maze[i][j] == 'M') 80 mx = i, my = j; 81 int ans = bfs(mx, my, yx, yy); 82 cout << ans << endl; 83 } 84 85 return 0; 86 }