迷宮問題 POJ - 3984(bfs+記錄路徑)


題目鏈接:http://poj.org/problem?id=3984

題意:從(0,0)走到(4,4)的最短路徑,該路僅一定存在

思路:記錄每個子節點的父節點的下標,從(4,4)結點依次往上尋找父節點,存到棧里,再用棧輸出

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <queue>
 5 #include <algorithm>
 6 #include <cmath>
 7 #include <map>
 8 #include <stack>
 9 #define mem(a,b) memset(a,b,sizeof(a));
10 using namespace std;
11 #define INF 0x3f3f3f3f
12 typedef long long ll;
13 int dir[4][2] = {0,1,0,-1,1,0,-1,0};
14 const int maxn = 2005;
15 int a[10][10],ans;
16 struct Node{
17     int x,y,t,ft;
18     Node(){};
19     Node(int x1,int y1,int t1,int f1):x(x1),y(y1),t(t1),ft(f1){};
20 }p[maxn];
21 
22 struct node {
23     int x,y;
24     node(int x1,int y1):x(x1),y(y1){};
25 };
26 bool vis[10][10];//標記該點是否走過,防止重復走
27 void bfs(int x,int y){
28     p[0].x = x,p[0].y = y,p[0].t = 0;
29     queue<Node>q;
30     q.push(Node(x,y,0,0));//起點入隊列
31     vis[x][y] = 1;
32     int k = 0;
33     while(!q.empty()) {
34         Node temp = q.front();
35         q.pop();
36         if(temp.x == 4 && temp.y == 4){
37             ans = temp.t;//找到最終結點的下標
38             break;
39         }
40         for(int i = 0; i < 4; i++) {
41             int sx = temp.x + dir[i][0], sy = temp.y + dir[i][1];
42             if(!vis[sx][sy] && a[sx][sy] == 0 && sx >=0 && sx < 5 && sy >= 0&& sy < 5) {
43                 k++;//數組里當前結點的下標
44                 vis[sx][sy] = 1;
45                // cout << sx << " " << sy <<endl;
46                 p[k].x = sx,p[k].y = sy,p[k].t = k, p[k].ft = temp.t;//ft存父節點的下標
47                 q.push(Node(p[k].x,p[k].y,p[k].t,p[k].ft));
48             }
49         }
50     }
51 }
52 int main()
53 {
54     for(int i = 0; i < 5; i++) {
55         for(int j = 0; j < 5; j++) {
56             cin >> a[i][j];
57         }
58     }//輸入
59     bfs(0,0);
60     stack<node>m;
61     int zx,zy;
62     zx = p[ans].x, zy = p[ans].y;//ans最后一個結點的坐標
63     m.push(node(zx,zy));//入棧
64     int zz;
65     while(1){
66         ans = p[ans].ft;//找到當前結點的父節點的下標
67         zz = p[ans].t;//當前結點
68         zx = p[ans].x, zy = p[ans].y;
69         m.push(node(zx,zy));//入棧
70         if(zz == 0)
71             break;//如果當前結點是起點,退出
72     }
73     while(!m.empty()) {//輸出
74         node temp = m.top();
75         m.pop();
76         cout << "(" << temp.x <<", "<<temp.y<<")" << endl;
77     }
78     return 0;
79 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM