迷宮路徑,輸出最短路徑(BFS)

題目:POJ - 3984

今天阿聰來到了一個滑雪勝地滑雪,但是這個時候前面出現了一座迷宮擋住了他的去路。 堅定的阿聰一定要穿過這座迷宮去滑雪! 爲了方便起見,我們定義一個二維數組來表示迷宮: 

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)

思路:從(0,0)開始,BFS搜索,記錄每一個可行點的前驅結點,最先達到(4,4)點後輸出路徑

code

#include<cstdio>
#include<algorithm>
#include<queue>
#include<stack>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn=10;

int maze[maxn][maxn];
int v[maxn][maxn];
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
struct path {

     int x,y;
     path (int _x, int _y){

          x=_x;
          y=_y;
     };
     path(){};

}p[maxn][maxn];
queue <path> q;

void print(){
   stack <path> s;
   path pa;
   pa.x=4; pa.y=4;
   while(1){
        s.push(pa);
        if(pa.x==0 && pa.y==0) break;
        pa =p[pa.x][pa.y];
   }
   while(!s.empty()){

    cout<<"("<<s.top().x<<","<<" "<<s.top().y<<")"<<endl;
    s.pop();

   }

}

void bfs(int h, int l)
{
    q.push(path(h,l));
    v[h][l]=1;
    while(!q.empty()){
        path tmp=q.front();
        q.pop();
        if(tmp.x==4&&tmp.y==4) {

                print(); return ;
        }
        for(int i=0;i<4;i++){
               int hh=tmp.x+dx[i];
               int ll=tmp.y+dy[i];
                if(hh>=0 && hh<5 && ll>=0 && ll<5 && v[hh][ll]==0 && maze[hh][ll]==0){
                             q.push(path(hh,ll));
                             p[hh][ll]=tmp;
                             v[hh][ll]=1;

           }
       }
    }
}
int main()
{
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
    scanf("%d",&maze[i][j]);

    memset(v,0,sizeof(v));

    bfs(0,0);

    return 0;
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章