You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1013 B

#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
const int N = 110;
int n, m;
int g[N][N];
int d[N][N];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
queue<PII> q;
int bfs() {
q.push({1, 1});
memset(d, -1, sizeof d);
d[1][1] = 0;
while (q.size()) {
if (~d[n][m]) break; // 不等于-1,表示已找到小哈,剪枝
auto u = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int tx = u.x + dx[i], ty = u.y + dy[i];
if (tx == 0 || tx > n || ty == 0 || ty > m) continue;
if (g[tx][ty] == 0 && d[tx][ty] == -1) {
d[tx][ty] = d[u.x][u.y] + 1;
q.push({tx, ty});
}
}
}
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 << bfs() << endl;
return 0;
}