题目链接
BFS(使用队列模拟)
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int N = 150;
int g[N][N],d[N][N];
int n,m;
typedef pair<int,int> PII;
int dfs()
{
queue<PII> q;
memset(d,-1,sizeof d);
d[1][1] = 0;
q.push({1,1});
int dx[4] = {-1,0,1,0},dy[4] = {0,-1,0,1};
while(q.size())
{
auto t = q.front();
q.pop();
for(int i = 0;i < 4;i ++)
{
int x = t.first + dx[i],y = t.second + dy[i];
if(x >= 1 && x <= n && y >= 1 && y <= m && g[x][y] == 0 && d[x][y] == -1)
{
d[x][y] = d[t.first][t.second] + 1;
q.push({x,y});
}
}
}
return d[n][m];
}
int main()
{
cin >> n >> m;
for(int i = 1;i <= n;i ++)
{
for(int j = 1;j <= m;j ++)
{
cin >> g[i][j];
}
}
cout << dfs() << endl;
return 0;
}