迷宫问题 (广搜+记录路径)

定义一个二维数组:

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)

开一个pre[][]数组来记录每一个点的前置结点,从终点倒着搜索,一直搜到起点,然后输出pre中的相关点就好了

#include<cstdio>
#include<queue>
using namespace std;
bool mapp[6][6];
struct Node
{
    int x, y;
}pre[6][6];
bool book[6][6];
int mv[4][2] = {{0,-1},{-1,0},{0,1},{1,0}};
void bfs()
{
    queue<Node> q;
    Node tmp,next;
    tmp.x = 4;
    tmp.y = 4;
    q.push(tmp);
    while(!q.empty())
    {
        if(tmp.x==0&&tmp.y==0)
            break;
        tmp = q.front();
        q.pop();
        int xt, yt;
        for(int i=0;i<4;i++)
        {
            xt = tmp.x + mv[i][0];
            yt = tmp.y + mv[i][1];
            if(xt<0||xt>4||yt<0||yt>4)
                continue;
            if(!book[xt][yt]&&!mapp[xt][yt])
            {
                next.x = xt;
                next.y = yt;
                pre[xt][yt].x = tmp.x;
                pre[xt][yt].y = tmp.y;
                q.push(next);
                book[xt][yt] = true;
            }
        }
    }
}
int main()
{
    int x, y;
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
        scanf("%d", &mapp[i][j]);
    bfs();
    x = 0;
    y = 0;
    int i,j;
    printf("(0, 0)\n");
    while(x!=4||y!=4)
    {
        i = pre[x][y].x;
        j = pre[x][y].y;
        printf("(%d, %d)", i,j);
        x = i;
        y = j;
        if(i!=4||y!=4)
            printf("\n");
    }
    return 0;
}
    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/qq_39091609/article/details/76084918
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞