poj3984迷宫问题(如何输出最短路)

题目:

迷宫问题

Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu

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], 记录(x,y)这个点的前驱是哪一个点。我们可以思考一下在入队时,假设在某个点有两条路径选择,分别为a, b, c, d和e, f, g, h, 那么在入队时,a入队,e入队,之后,a出队,b入队,那么b的前驱是a,e出队,f入队,f的前驱是e,不难理解,前驱能保存路径。这样我们在知道结束位置的情况下,就可以逆向输出得到答案了。额,怎样逆向输出呢?写个栈吧,路子野了点,我比较low

代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>

using namespace std;

struct node{
    int x, y;
};


int arr[5][5];
bool vis[5][5];
int dx[4] = {0, 1, -1, 0};
int dy[4] = {1, 0, 0, -1};
node pre[10][10];


void print(){
    stack<node> zhan;
    node lrh{4, 4};

    while(1){
        zhan.push(lrh);
        if(lrh.x==0 && lrh.y==0) break;
        lrh = pre[lrh.x][lrh.y];
    }

    while(!zhan.empty()){
        cout<<"("<<zhan.top().x<<", "<<zhan.top().y<<")"<<endl;
        zhan.pop();
    }
}

void bfs(int x, int y){
    queue<node> q;
    q.push(node{x, y});
    vis[x][y] = true;
    while(!q.empty()){
        node tmp = q.front();
        q.pop();
        if(tmp.x==4&&tmp.y==4) { print(); return;}
        for(int i=0; i<4; i++){
            int now_x = tmp.x + dx[i];
            int now_y = tmp.y + dy[i];
            if(0<=now_x && now_x<5 && 0<=now_y && now_y<5 && !vis[now_x][now_y] && arr[now_x][now_y]==0){
                q.push(node{now_x, now_y});
                pre[now_x][now_y] = tmp;
                vis[now_x][now_y] = true;
            }
        }
    }
}


int main(){
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    memset(arr, 0, sizeof(arr));
    for(int i=0; i<5; i++)
        for(int j=0; j<5; j++)
            cin>>arr[i][j];

    memset(vis, false, sizeof(vis));
    memset(pre, 0, sizeof(pre));

    bfs(0, 0);

    return 0;
}
    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/qq_33279781/article/details/51991835
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞