给定一个 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
思路:
这道题其实就是多了个判断条件g[i][j]只有为0时这个点才能走,并且多了一个dis 数组来记录需要 多少步才能到达右下角
代码实现:
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N=105;
int g[N][N];
bool vis[N][N];
int dis[N][N];
int n,m;
int jump[4][4]={{1,0},{-1,0},{0,1},{0,-1}};
void bfs()
{
queue<PII>q;
q.push({0,0});
vis[0][0]=true;
dis[0][0]=0;
while(!q.empty())
{
PII t=q.front();
q.pop();
int tx=t.first; int ty=t.second;
for(int i=0;i<4;i++)
{
int X=tx+jump[i][0];
int Y=ty+jump[i][1];
if(!vis[X][Y] && g[X][Y]==0 && X>=0 && X<n && Y>=0 && Y<m)
{
vis[X][Y]=true;
dis[X][Y]=dis[tx][ty]+1;
if(X==n-1 && Y==m-1) return;
q.push({X,Y});
}
}
}
}
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cin>>g[i][j];
bfs();
cout<<dis[n-1][m-1]<<endl;
return 0;
}