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


題目鏈接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=105278#problem/K

K - 迷宮問題
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit  Status

Description

定義一個二維數組: 

int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};

它表示一個迷宮,其中的1表示牆壁,0表示可以走的路,只能橫着走或豎着走,不能斜着走,要求編程序找出從左上角到右下角的最短路線。

Input

一個5 × 5的二維數組,表示一個迷宮。數據保證有唯一解。

Output

左上角到右下角的最短路徑,格式如樣例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

題解:注意暴力搜索記錄路徑的題,一個學到的很好的方法就是開一個數組記錄當前節點的父親節點,然后最后輸出的時候,從最后一個點依次向前面找,按照父親找父親的方法找下去,最后就是路徑了
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<stack>
 4 #include<queue>
 5 #include<string>
 6 using namespace std;
 7 int mp[5][5];
 8 struct Node{
 9     int x;
10     int y;
11 };
12 Node fa[5][5];
13 bool vis[5][5];
14 bool ck(Node k)
15 {
16     if(k.x<=4&&k.x>=0&&k.y>=0&&k.y<=4) return true;
17     return false;
18 }
19 
20 int go[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
21 
22 void bfs(){
23     queue<Node>q;
24     memset(vis,0,sizeof(vis));
25     Node tm;
26     tm.x = 0;
27     tm.y = 0;
28     q.push(tm);
29     vis[0][0] = 1;
30     while(!q.empty()){
31         Node tm1 = q.front();q.pop();
32         Node fl;
33         for(int i = 0; i < 4; i++){
34             fl.x = tm1.x+go[i][0];
35             fl.y = tm1.y+go[i][1];
36             if(ck(fl)&&vis[fl.x][fl.y]==0&&mp[fl.x][fl.y]==0){
37                 q.push(fl);
38                 vis[fl.x][fl.y] = 1;
39                 fa[fl.x][fl.y] = tm1;
40             }
41         }
42     }
43 }
44 
45 int main()
46 {
47     for(int i = 0; i < 5; i++)
48         for(int j = 0; j < 5; j++)
49             scanf("%d",&mp[i][j]);
50     bfs();
51     stack<Node>v;
52     Node ff = fa[4][4];
53     while(!(ff.x==0&&ff.y==0)){
54         v.push(ff);
55         ff = fa[ff.x][ff.y];
56     }
57     printf("(0, 0)\n");
58     while(!v.empty()){
59         printf("(%d, %d)\n",v.top().x,v.top().y);
60         v.pop();
61     }
62     printf("(4, 4)\n");
63     return 0;
64 }

 


免責聲明!

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



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