思路:
(1)一方面通过bfs()逐层寻找所有可行路径;另一方面通过d记录走过距离,由于是等权bfs,所以距离为最短距离。
(2)bfs是通过队列实现的,先将起点放到队列里,同步维护d,每次探讨所有可能的下一步,如果符合条件(既不越界,也不是走过的格子,也不是障碍物)就走过去,一方面记录d,另一方面将其放到队列里备用;直到走到目标地点或者队列为空即所有路都探索完了,则bfs停止。
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e2 + 10;
int a[N][N],d[N][N];
typedef pair<int,int> PII;
int n,m;
int dx[] = {0,0,1,-1},dy[] = {1,-1,0,0};
void bfs()
{
queue<PII> q;
memset(d,-1,sizeof d);
d[1][1] = 0;
q.push({1,1});
while(!q.empty())
{
PII tmp = q.front();
q.pop();
int x = tmp.first,y = tmp.second;
for(int i = 0;i < 4;i ++)
{
int tx = x + dx[i],ty = y +dy[i];
if(tx > 0 && ty > 0 && tx <= n && ty <= m && d[tx][ty] == -1 && a[tx][ty] != 1)
{
d[tx][ty] = d[x][y] + 1;
q.push({tx,ty});
}
}
}
cout << d[n][m]<<endl;
}
int main()
{
cin >> n >> m;
for(int i = 1;i <= n;i ++)
for(int j = 1;j <= m;j ++)
{
cin >> a[i][j];
}
bfs();
return 0;
}