代码:
#include <bits/stdc++.h>
using namespace std;
int n,m,x1,y0t,x2,y2,ans = 2.1e9,a[15][15];
bool v[15][15];
void dfs(int x,int y,int bl,int s)
{
if (s > ans || bl == 0 || v[x][y] || x > n || x < 1 || y > m || y < 1 || a[x][y] == 0) return;
v[x][y] = 1;
if (x == x2 && y == y2)
{
ans = min(s,ans);
return;
}
if (a[x][y] == 4) bl = 6;
bl--;
s++;
dfs(x - 1,y,bl,s);
dfs(x,y - 1,bl,s);
dfs(x + 1,y,bl,s);
dfs(x,y + 1,bl,s);
v[x][y] = 0;
}
int main()
{
cin >> n >> m;
for (int i = 1;i <= n;i++)
for (int j = 1;j <= m;j++)
{
scanf("%d",&a[i][j]);
if (a[i][j] == 2) x1 = i,y0t = j;
if (a[i][j] == 3) x2 = i,y2 = j;
}
dfs(x1,y0t,6,0);
if (ans > 2e9) cout << -1;
else cout << ans;
return 0;
}