迷宫问题 题解
迷宫问题
定义一个二维数组:
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 0Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
BFS算法(输出路径):
#include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;
int mp[5][5],vis[5][5];
int fx[4]={1,0,-1,0};
int fy[4]={0,1,0,-1}; 
struct node
{
    int x,y;
}s[5][5];
void fun(int x,int y)//举例解释若x=4,y=4 
{
    if(x==0 && y==0) return ;
    //一直返回到(0,0),结束中间每一个fun,执行打印语句 
    fun(s[x][y].x,s[x][y].y);
    //fun得是(3,4),因为某点里存的是它从哪个点来的 
    cout<<"("<<s[x][y].x<<", "<<s[x][y].y<<")"<<endl;
    return ;
}
bool check(int x,int y)
{
    if(x>=0 && x<5 && y>=0 && y<5 &&  mp[x][y]==0)
        return 1;
    return 0;
}
void bfs(int x,int y)
{
    queue<node> q;
    q.push({x,y});
    while(q.size())
    {
        node now=q.front();
        vis[now.x][now.y]=1;
        q.pop();
        if(now.x==4 && now.y==4){
            fun(4,4);//从终点向前找到起点开始输出 
            return ;
        }
        for(int i=0;i<4;i++)
        {
            int nextx=now.x+fx[i];
            int nexty=now.y+fy[i];
            if(!vis[nextx][nexty] && check(nextx,nexty))
            {
                s[nextx][nexty].x=now.x;//记录这个点是从哪来的 
                s[nextx][nexty].y=now.y;
                q.push({nextx,nexty});
            }
        }
    }
    cout<<"NO"<<endl;
}
int main()
{
    ios_base::sync_with_stdio(false);
    for(int i=0;i<5;i++)
    {
        for(int j=0;j<5;j++)
        {
            cin>>mp[i][j];
        }
    }
    vis[0][0]=1;
    bfs(0,0);
    cout<<"(4, 4)"<<endl;
    return 0;
}
PS:这个bfs算法可以输出路径,关键的地方就是要记录这个点是从哪来的,也就是记录它上一个点的坐标,而下标存这个点的坐标

                
            
        
浙公网安备 33010602011771号