这是一道Acwing的BFS模板题,我自己的代码跟Acwing的题解代码差不了多少,但就是没输出,望有大佬能解答。蒟蒻会给每位回答的大佬都点上关注。谢谢!
给定一个 n×m 的二维整数数组,用来表示一个迷宫,数组中只包含 0 或 1,其中 0 表示可以走的路,1 表示不可通过的墙壁。
最初,有一个人位于左上角 (1,1) 处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。
请问,该人从左上角移动至右下角 (n,m) 处,至少需要移动多少次。
数据保证 (1,1) 处和 (n,m) 处的数字为 0,且一定至少存在一条通路。
第一行包含两个整数 n 和 m。
接下来 n 行,每行包含 m 个整数(0或1),表示完整的二维数组迷宫。
输出一个整数,表示从左上角移动至右下角的最少移动次数。
1≤n,m≤100
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<bits/stdc++.h>
using namespace std;
const int N=110;
typedef pair<int,int> PII; //横纵坐标
int a[N][N],f[N][N]; //a为存图的邻接矩阵,f[i][j]表示到点1,1到点i,j的最短距离
int n,m;
int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0}; //偏移量数组,上右下左
queue <PII> q; //存当前轮所能延伸的点的坐标
void bfs(int x,int y){ //输入起点坐标
q.push({x,y});
f[0][0]=0;
while(!q.empty()){
PII po=q.front();
q.pop();
a[po.first][po.second]=1; //用了就变成墙以防走回去
for(int i=0;i<4;i++){ //上下左右四方向
int nx=po.first+dx[i],ny=po.second+dy[i];
if(a[nx][ny]==0){
f[nx][ny]=f[po.first][po.second]+1;
q.push({nx,ny}); //加入新点
}
}
}
return;
}
int main(){
cin>>n>>m;
memset(f,1,sizeof(f));
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
bfs(1,1);
cout<<f[n][m];
return 0;
}