bfs(模板)

主要求最短路

844. 走迷宫 - AcWing题库

#include<bits/stdc++.h>
#define int long long 
using  namespace std;
int a[110][110];
bool check[110][110];
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
int w[110][110];

int n,m;
typedef pair<int, int> PII;
PII c[110][110];
int  bfs()
{
    queue<PII>q;
    q.push({1,1});
    check[1][1]=1;
    while(!q.empty())
    {
       PII p=q.front();
       q.pop();
       for(int i=0;i<4;i++)
       {   int x=p.first+dx[i];
           int y=p.second+dy[i];
           
           if(a[x][y]==0 && !check[x][y]&&x<=n&&y<=m&&x>=1&&y>=1)
           {   c[x][y]=p;
               check[x][y]=1;
               w[x][y]=w[p.first][p.second]+1;
               q.push({x,y});
           }
       }
    }
    
  //  int x=n,y=m;//返回路径
  //    while(x||y)
    //{
      //  cout<<x<<" "<<y<<endl;
        //auto t=c[x][y];
    //    x=t.first;y=t.second;
    //}
    
    
    
    cout<<w[n][m];
}



signed main()
{
    
  
    
    cin>>n>>m;
    for(int i=1;i<=n;i++)
     for(int j=1;j<=m;j++)
      cin>>a[i][j];
   bfs();
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值