迷宫路径,输出最短路径(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;
}

 

 

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