BFS
有个小剪枝,对于BFS第一次到达的点才操作,不然就终止。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 101;
int m, n;
int g[N][N];
int c[N][N];
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
int res = 0x3f3f3f3f;
void bfs(){
queue<PII> q;
memset(c, -1, sizeof c);
q.push({0, 0});
c[0][0] = 0;
while(q.size()){
auto t = q.front();
q.pop();
int u = t.first, v = t.second;
g[u][v] = 1;
for(int i = 0 ; i < 4; i++){
int a = u + dx[i], b = v + dy[i];
if(a>=0 && b>=0 && a<m && b <n && g[a][b]==0 && c[a][b]==-1){ //剪枝c[a][b]==-1
q.push({a, b});
c[a][b] = c[u][v] + 1;
}
}
}
}
int main(){
cin>>m>>n;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cin>>g[i][j];
}
}
bfs();
cout<<c[m-1][n-1]<<endl;
return 0;
}