1. 程式人生 > >POJ-3984-迷宮問題(BFS)

POJ-3984-迷宮問題(BFS)

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.BFS,需要注意的就是列印的是路徑點。所以需要儲存路徑最後再輸出。儲存路徑:在走每一個節點時記錄它的父節點的編號。

2.當然因為這個題就一組資料可以肉眼觀測打表做...


 1 #include<cstdio>
 2 #include<queue>
 3 using namespace std;
 4 int map[5][5];
 5 int dir[4][2]={{1,0},{0,-1},{-1,0},{0,1}};
 6 
 7 struct node{
 8     int x,y,pre,n;//n為編號,pre為父節點的編號
 9 }p[100];
10 
11
void print(int i){ 12 if(p[i].pre!=-1) { 13 print(p[i].pre); 14 printf("(%d, %d)\n",p[i].x,p[i].y); 15 } 16 else{ 17 printf("(%d, %d)\n",p[i].x,p[i].y); 18 } 19 } 20 21 void bfs(){ 22 int cnt=0; 23 p[cnt].x=0,p[cnt].y=0,p[cnt].pre=-1; 24 map[0][0]=1; 25
queue<node>q; 26 node head,next; 27 head.x=0,head.y=0,head.n=0; 28 q.push(head); 29 while(!q.empty()){ 30 31 head=q.front(); 32 q.pop(); 33 34 if(head.x==4&&head.y==4){ 35 print(cnt); 36 return; 37 } 38 39 for(int i=0;i<4;i++){ 40 next.x=head.x+dir[i][0]; 41 next.y=head.y+dir[i][1]; 42 43 if(next.x<0||next.x>4||next.y<0||next.y>4||map[next.x][next.y]) continue; 44 45 map[next.x][next.y]=1; 46 cnt++; 47 next.n=cnt; 48 p[cnt].x=next.x,p[cnt].y=next.y; 49 p[cnt].pre=head.n; 50 q.push(next); 51 } 52 } 53 } 54 55 int main(){ 56 for(int i=0;i<5;i++) 57 for(int j=0;j<5;j++) 58 scanf("%d",&map[i][j]); 59 bfs(); 60 return 0; 61 }

 打表:

1 #include<cstdio>
2 using namespace std;
3 int main(){
4     printf("(0, 0)\n(1, 0)\n(2, 0)\n(2, 1)\n(2, 2)\n(2, 3)\n(2, 4)\n(3, 4)\n(4, 4)\n");
5     return 0;
6 }