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)

Source

bfs 输出路径

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<stack>
#define maxn 20
#define maxm 10000
int num[maxn][maxn];
int vis[maxn][maxn];
int dis[maxn][maxn];
int pre[maxn][maxn];
int cnt;
using namespace std;
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
struct node
{
    int a,b;
    node(){}
    node(int a,int b):a(a),b(b){}

}
nodes[maxm];
struct Ceil
{
    int a,b;
    Ceil()
    {

    }
    Ceil(int a,int b):a(a),b(b){}
};
Ceil bfs()
{
    cnt=0;
    queue<Ceil>q;
    memset(vis,0,sizeof(vis));
    while(!q.empty())

    dis[0][0]=0;
    vis[0][0]=1;
    q.push(Ceil(0,0));
    Ceil u;

    while(!q.empty())
    {
        u=q.front();
        q.pop();
        int a=u.a,b=u.b;

        int xx,yy;
        for(int i=0;i<4;i++)
        {
            xx=a+dx[i];
            yy=b+dy[i];
                   if(!vis[xx][yy]&&num[xx][yy]==0&&xx>=0&&xx<5&&yy>=0&&yy<5)

            {vis[xx][yy]=1;
            dis[xx][yy]=dis[a][b]+1;

            nodes[cnt++]=node(a,b);
            pre[xx][yy]=cnt-1;
            if(xx==4&&yy==4)
            {
                return Ceil(xx,yy);
            }
            q.push(Ceil(xx,yy));
        }
}
    }

    return Ceil(-1,-1);
}
int main()
{
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
            scanf("%d",&num[i][j]);
        Ceil ceil=bfs();



        stack<node>s;
        int a=4;
        int b=4;
        s.push(node(a,b));
        while(a!=0||b!=0)
        {
            int p=pre[a][b];


            s.push(nodes[p]);
            a=nodes[p].a;
            b=nodes[p].b;
        }

        while(!s.empty())
        {
            node x=s.top();
            s.pop();
            int r=x.a;
         int c=x.b;
         printf("(%d, %d)\n",r,c);


        }
        return 0;
    }

猜你喜欢

转载自blog.csdn.net/sdauguanweihong/article/details/84231002
今日推荐