#include<bits/stdc++.h>
#include<queue>
using namespace std;
const int N=10010;
typedef pair<int,int> PII;
int mp[N][N];//地图
int dis[N][N];//每一个点到起点的距离
int n,m;
int dx[4]={0,1,0,-1};
int dy[4]={-1,0,1,0};
queue<PII>q;
int bfs()
{
memset(dis,-1,sizeof dis);
q.push({0,0});
dis[0][0]=0;
while(!q.empty())
{
PII top =q.front();
for(int i=0;i<4;i++)
{
int x = top.first + dx[i];
int y = top.second +dy[i];
if(x>=0&&x<n&&y>=0&&y<m&&mp[x][y]==0&&dis[x][y]==-1)
{
dis[x][y]=dis[top.first][top.second]+1;
q.push({x,y});
}
}
q.pop();
}
return dis[n-1][m-1];
}
signed main()
{
ios::sync_with_stdio(0);cin.tie(0);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>mp[i][j];//读入地图
cout<<bfs();
return 0;
}
宽度优先搜索模板(bfs)
于 2024-07-11 17:07:22 首次发布