AcWing 844 走迷宫 BFS模板题

题目描述

在这里插入图片描述

输入格式

在这里插入图片描述

输出格式

在这里插入图片描述

数据范围

在这里插入图片描述

输入样例

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

输出样例

8

#include <iostream>
#include <queue>

using namespace std;
const int N = 110;
struct node
{
    int x,y;
};//结构体存坐标
int n1,m1;
int m[N][N];//map地图
int d[N][N];//到起点的距离
void bfs(int a,int b)
{
    queue<node>q;
    q.push({a,b});
    while(!q.empty())
    {
        node st=q.front();//记录当前坐标
        //cout<<st.x<<","<<st.y<<endl;
        q.pop();
        m[st.x][st.y]=1;//走过后标记
        int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0};
        for(int i = 0; i < 4; i++)//遍历4个方向
        {
            int x=st.x+dx[i];
            int y=st.y+dy[i];
            // cout<<"("<<x<<","<<y<<")"<<" ";
            if(m[x][y] == 0&&x>=1&&y>=1&&x<=n1&&y<=m1)//防止越界
            {
                m[x][y]=1;//标记
                d[x][y]=d[st.x][st.y]+1;//下一个距离+1
                q.push({x,y});//如果能走,存入该方向的点
            }
        }
    }
    cout<<d[n1][m1];
}
int main()
{
    cin>>n1>>m1;
    for(int i = 1; i <= n1; i++)
    {
        for(int j = 1; j <= m1; j++)
        {
            cin >> m[i][j];
        }
    }
    bfs(1,1);
    return 0;
}

bfs模板题,从起点开始广搜,记录下一点到起点的距离

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值