C++迷宫问题

定义一个二维数组 N*M ,如 5 × 5 数组下所示:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的路线。入口点为[0,0],既第一格是可以走的路。

输入描述:

输入两个整数,分别表示二维数组的行数,列数。再输入相应的数组,其中的1表示墙壁,0表示可以走的路。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。

输出描述:

左上角到右下角的最短路径,格式如样例所示。

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
int main()
{
    int n,m;
    cin>>n>>m;
    vector<vector<int>>maze(n,vector<int>(m,0));
    for(int i=0;i<n;i++)//元素入数组
    {
        for(int j=0;j<m;j++)
        {
            int temp;
            cin>>temp;
            maze[i][j]=temp;
        }
    }
    int dx[4]={0,1,0,-1};
    int dy[4]={1,0,-1,0};
    vector<vector<int>>vis(n,vector<int>(m,0)); //访问数组,0未访问,1已访问
    queue<pair<int,int>>que;//创建队列
    que.push(make_pair(0,0));//起点元素入队列
    vis[0][0]=1;  //起点元素设置为已访问
    pair<int,int>father[n][m];//记录当前下标的父下标
    while(!que.empty())
    {
        pair<int,int>now;
        now=que.front();
        que.pop();
        if(now.first==n-1 && now.second==m-1)
        {
            break;
        }
        for(int i=0;i<4;i++)
        {
            int tx=now.first+dx[i];//下一个点
            int ty=now.second+dy[i];
            if(tx>=0 && tx<n && ty>=0 && ty<m && maze[tx][ty]!=1 && vis[tx][ty]==0)//边界设置及未访问
            {
                vis[tx][ty]=1;//设置为已访问
                que.push(make_pair(tx,ty));//下一轮入队列
                father[tx][ty]={now.first,now.second};//tx,ty的父节点是now
            }
        }
        
    }
    //路径输出
    stack<pair<int,int>>st;
    st.push({n-1,m-1});
    int i=n-1,j=m-1;
    while(i!=0 || j!=0)
    {
        pair<int,int>f=father[i][j];//查找父节点
        i=f.first;
        j=f.second;
        st.push(f);
    }
    while(!st.empty())//输出栈
    {
        cout<<'('<<st.top().first<<','<<st.top().second<<')'<<endl;
        st.pop();
    }

    
}

迷宫问题_牛客题霸_牛客网【牛客题霸】收集各企业高频校招笔面试题目,配有官方题解,在线进行百度阿里腾讯网易等互联网名企笔试面试模拟考试练习,和牛人一起讨论经典试题,全面提升你的技术能力https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc?tpId=37&tqId=21266&rp=1&ru=/ta/huawei&qru=/ta/huawei&difficulty=3&judgeStatus=&tags=/question-ranking

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值