BFS
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N = 105;
int p[N][N], d[N][N];
int n, m;
queue<pair<int,int>> que;
int bfs(){
memset(d, -1, sizeof d);
d[0][0] = 0;
int a[4] = {-1, 0, 1, 0}, b[4] = {0, -1, 0, 1};
while (!que.empty()) {
auto t = que.front();
que.pop();
for (int i = 0; i < 4; i++){
int x = t.first + a[i], y = t.second + b[i];
if (x >= 0 && x < n && y >= 0 && y < m && d[x][y] == -1&& p[x][y] == 0){
que.push({x, y});
d[x][y] = d[t.first][t.second] + 1;
}
}
}
return d[n-1][m-1];
}
int main(){
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i ++) for (int j = 0; j < m; j ++) scanf("%d", &p[i][j]);
que.push(make_pair(0,0));
cout << bfs();
}总结
最后更新于