[kuangbin带你飞]专题一 简单搜索 K - 迷宫问题

K - 迷宫问题

定义一个二维数组: 
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)


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int Map[6][6];
int dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
int st=0,en=1;//起点,终点
struct node
{
    int x,y,pre;//此点的横纵坐标和从哪一个点走来的
}p[105];
int print(int i)
{
    if(p[i].pre!=-1)//递归打印,不断找前一个走道的点,直到到起点为止
    {
        print(p[i].pre);
        printf("(%d, %d)\n",p[i].x,p[i].y);
    }
}
void bfs(int n,int m)
{
    p[st].x=n;//第一个点,pre=-1,方便之后输出答案
    p[st].y=m;
    p[st].pre=-1;
    while(st<en)
    {
        for(int i=0;i<4;i++)//走四个方向,能走的每个点都是由st走到的,所以它们的pre都是st
        {
            int a=p[st].x+dir[i][0];
            int b=p[st].y+dir[i][1];
            if(a>=0&&a<=4&&b>=0&&b<=4&&!Map[a][b])
            {
                Map[a][b]=1;
                p[en].x=a;
                p[en].y=b;
                p[en].pre=st;
                en++;
            }
            if(a==4&&b==4)
                print(st);//从走到终点的前一步开始打印
        }
        st++;
    }
}
int main()
{
    for(int i=0;i<=4;i++)
    {
        for(int j=0;j<=4;j++)
        {
            cin>>Map[i][j];
        }
    }
    printf("(0, 0)\n");
    bfs(0,0);
    printf("(4, 4)\n");
    return 0;
}




猜你喜欢

转载自blog.csdn.net/qq_41037114/article/details/80964438