POJ - 3984迷宫问题(最短路径输出)

题目链接:http://poj.org/problem?id=3984

题目:

迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 35034 Accepted: 19912

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可以很简单求出最短路径的值,但是又怎样输出它的最短路径呢?我们可以开个node类型的二维数组pre[x][y],记录每个节点的前驱顶点是哪个顶点。因为每个节点的前驱节点是唯一的,只会是最快到达它的那个顶点,而每个节点的后继节点却不唯一,它可能可以朝各个方向走,所以记录它的前驱节点是可行的。然后就是输出问题,我们需要递归逆序输出就可以了。
附上代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int mp[5][5],vis[5][5];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node{
    int x,y;
};
node pre[10][10];
void BFS()
{
    queue<node> que;
    node str;
    str.x=str.y=0;
    que.push(str);
    vis[0][0]=1;
    while(!que.empty())
    {
        node now=que.front();
        que.pop();
        if(now.x==4&&now.y==4)
            return;
        for(int i=0;i<4;i++)
        {
            node next;
            next.x=now.x+dir[i][0];
            next.y=now.y+dir[i][1];
            if(next.x>=0&&next.x<5&&next.y>=0&&next.y<5&&!mp[next.x][next.y]&&!vis[next.x][next.y])
            {
                vis[next.x][next.y]=1;
                que.push(next);
                pre[next.x][next.y]=now;
            }
        }
    }
}
void print(node cur)
{
    if(cur.x==0&&cur.y==0)
    {
        printf("(0, 0)\n");
        return;
    }
    print(pre[cur.x][cur.y]);   //逆序输出
    printf("(%d, %d)\n",cur.x,cur.y);
}
int main()
{
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
            scanf("%d",&mp[i][j]);
    BFS();
    node ed;
    ed.x=ed.y=4;
    print(ed);
    return 0;
}

 



转载于:https://www.cnblogs.com/zjl192628928/p/9794771.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值