给定一个 n×mn×m 的二维整数数组,用来表示一个迷宫,数组中只包含 00 或 11,其中 00 表示可以走的路,11 表示不可通过的墙壁。
最初,有一个人位于左上角 (1,1)(1,1) 处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。
请问,该人从左上角移动至右下角 (n,m)(n,m) 处,至少需要移动多少次。
数据保证 (1,1)(1,1) 处和 (n,m)(n,m) 处的数字为 00,且一定至少存在一条通路。
输入格式
第一行包含两个整数 nn 和 mm。
接下来 nn 行,每行包含 mm 个整数(00 或 11),表示完整的二维数组迷宫。
输出格式
输出一个整数,表示从左上角移动至右下角的最少移动次数。
数据范围
1≤n,m≤1001≤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
思路:bfs。
#include<iostream>
#include<algorithm>
#include<cstring> //memset函数的库函数
using namespace std;
const int N=110;
pair<int,int> q[N*N];//是n*n对整数,引用时用q.first,q.second,定义了队列
int n,m;//n行m列
int g[N][N];//用来存图
int d[N][N];//用来存各个点到原点的距离
int bfs(){
int hh=0,tt=0;//队头是hh,队尾是tt
q[0]={0,0};//q存储坐标
memset(d,-1,sizeof(d)); //先把距离都初始化为-1,表示这个点没有走过
d[0][0]=0;//00点的距离初始化为0
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};//分别沿上右下左四个方向xy坐标的变化
while(hh<=tt){//当队列不空时
pair<int,int> t=q[hh++];//取出队头元素 t.first=q.first,t.second=q.second,h++
for(int i=0;i<4;i++){
int x=t.first+dx[i],y=t.second+dy[i];//x表示这个点往下走的横坐标,y表示纵坐标
if(x>=0&&x<n&&y>=0&&y<m&&g[x][y]==0&&d[x][y]==-1){//当这个点在边界内且能走且没走过时
d[x][y]=d[t.first][t.second]+1;
q[++tt]={x,y};//把刚刚那个点存入q中
}
}
}
return d[n-1][m-1];
}
int main(){
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%d",&g[i][j]);
}
}//把图存进来
printf("%d",bfs());
return 0;
}
注:思路来自acwing