给定一个 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 <cstring>
#include <algorithm>
#include <string>
#include <cmath>
#include <queue>
using namespace std;
typedef unsigned long long ull;
const int N = 1000010,P=1e9+7 ;
int n, m,len=1;
int a[110][110],dist[110][110];
bool st[110][110];
struct node
{
int x,y;
int move;
} ;
int dx[]= {0,0,1,-1},dy[]={1,-1,0,0};
void bfs()
{
// dist[bx][by]=0;
queue<node>q;
q.push({1,1,0});
//q.push({bx,by});
st[1][1]=true;
//st[bx][by]=true;
while(q.size())
{
node t=q.front();
q.pop();
if(t.x==n&&t.y==m)//走到终点,输出
{
cout<<t.move;
break;
}
for(int i=0;i<4;i++)//走上下左右四个方向
{
int ix=t.x+dx[i],iy=t.y+dy[i];
if(ix>=1&&ix<=n&&iy>=1&&iy<=m)//判断是否越界
{
if(!st[ix][iy]&&a[ix][iy]!=1)//判断有没有走过和是否有障碍物
{
st[ix][iy]=true;
q.push({ix,iy,t.move+1});
//dist[ix][iy]=dist[t.x][t.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];
}
}
bfs();
//cout<<dist[n][m];
return 0;
}