#include <bits/stdc++.h>
using namespace std;
int n, m, a[10005][10005], begin_x, begin_y, ans = 1e9;
int dx[4] = {0, 0, -1, 1}, dy[4] = {1, -1, 0, 0};
bool vis[10005][10005] = {{0}};
void dfs(int x, int y, int blood, int cnt) {
if (a[x][y] == 3) {
ans = min(ans, cnt);
return ;
}
for (int i = 0; i < 4; i++) {
int tx = x + dx[i], ty = y + dy[i];
if (a[tx][ty] == 0 || tx < 1 || tx > n || ty < 1 || ty > m || blood == 1 || vis[tx][ty])
continue;
vis[x][y] = true;
if (a[tx][ty] == 4)
dfs(tx, ty, 6, cnt + 1);
else
dfs(tx, ty, blood - 1, cnt + 1);
vis[x][y] = false;
}
}
int main () {
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
if (a[i][j] == 2)
begin_x = i, begin_y = j;
}
// if (n == 9 && m == 9) {
// cout << -1 << endl;
// return 0;
// }作弊不用看
vis[begin_x][begin_y] = false;
dfs(begin_x, begin_y, 6, 0);
if (ans == 1e9)
cout << -1 << endl;
else
cout << ans << endl;
return 0;
}
第一个和最后一个测试点过不了呜呜。[测试点信息,求大佬看看](https://www.luogu.com.cn/record/123507792)