给定一个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<iostream>
#include<queue>
using namespace std;
const int N=105;
int a[N][N];
int dis[4][2]={0,1,1,0,-1,0,0,-1};
int n,m;
struct node{
int x,y,step;
};
bool check(int x,int y){
if(x<1||x>n||y<1||y>m||a[x][y]==1)
return false;
else
return true;
}
int bfs(){
node start;
start.x=1;
start.y=1;
start.step=0;
queue<node>q;
q.push(start);
while(!q.empty()){
start=q.front();
q.pop();
node next;
for(int i=0;i<4;i++){
next.x=start.x+dis[i][0];
next.y=start.y+dis[i][1];
if(next.x==n&&next.y==m)
return start.step+1;
if(check(next.x,next.y)){
next.step=start.step+1;
q.push(next);
a[next.x][next.y]=1;
}
}
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>a[i][j];
cout<<bfs()<<endl;
return 0;
}