POJ 3984 迷宫问题

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)

水题。。BFS一次,每个点记录其前驱的位置,再倒一下输出即可,代码如下:

#include<iostream>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;
typedef struct node
{
    int x,y;
    node(int xx=0,int yy=0):x(xx),y(yy){}
}node;
node path[10][10];
bool r[10][10];
int d[4][2]={-1,0,0,1,1,0,0,-1};
int Map[10][10]={0};
bool ok(int x,int y)
{
    return x>=1&&x<=5&&y>=1&&y<=5&&Map[x][y]!=1;
}
void BFS()
{
    queue<node> q;
    memset(r,false,sizeof(r));
    node t;
    q.push(node(1,1));
    r[1][1]=true;
    while(!q.empty())
    {
        t=q.front(),q.pop();
        for(int i=0;i<4;++i)
        {
            int u=t.x+d[i][0],v=t.y+d[i][1];
            if(ok(u,v)&&!r[u][v])
            {
                r[u][v]=true;
                path[u][v].x=t.x,path[u][v].y=t.y;
                q.push(node(u,v));
                if(u==5&&v==5) return;
            }
        }    }
}
void Find()
{
    stack<node> s;
    int u,v,x,y;
    node t;
    u=v=5;
    while(u!=1||v!=1)
    {
        s.push(node(u,v));
        x=u,y=v;
        u=path[x][y].x,v=path[x][y].y;
    }
    s.push(node(1,1));
    while(!s.empty())
    {
        t=s.top(),s.pop();
        cout<<"("<<t.x-1<<", "<<t.y-1<<")"<<endl;
    }
}
int main()
{
    for(int i=1;i<=5;++i)
    {
        for(int j=1;j<=5;++j) cin>>Map[i][j];
    }
    BFS();
    Find();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值