#include <bits/stdc++.h>
using namespace std;
struct node{
int x,y,hp,step;
};
int n,m,sx,sy,ans = 0x3f3f3f3f;
int mp[114][514],vis[114][514];
int dir[4][2] = {0,1,0,-1,1,0,-1,0};
queue<node> que;
//void dfs(int x,int y,int hp,int step){
// for(int i = 0;i < 4;i++){
// int tx = x + dir[i][0];
// int ty = y + dir[i][1];
// if(tx < 1 || tx > n || ty < 1 || ty > m || vis[tx][ty] || mp[tx][ty] == 0)
// continue;
// int nh = hp - 1;
// if(nh <= 0)
// return;
// if(mp[tx][ty] == 3)
// ans = min(ans,step + 1);
// if(mp[tx][ty] == 4)
// nh = 6;
// vis[tx][ty] = 1;
// dfs(tx,ty,nh,step + 1);
// vis[tx][ty] = 0;
// }
//}
int bfs(){
vis[sx][sy] = 1;
que.push({sx,sy,6,0});
while(!que.empty()){
node now = que.front();
que.pop();
for(int i = 0;i < 4;i++){
node next = now;
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
if(next.x < 1 || next.x > n || next.y < 1 || next.y > m || vis[next.x][next.y] || mp[next.x][next.y] == 0 || now.hp <= 1)
continue;
next.hp = now.hp - 1;
next.step++;
if(mp[next.x][next.y] == 3)
return next.step;
if(mp[next.x][next.y] == 4)
next.hp = 6;
vis[next.x][next.y] = 1;
que.push(next);
}
}
return -1;
}
int main(){
cin >> n >> m;
for(int i = 1;i <= n;i++){
for(int j = 1;j <= m;j++){
cin >> mp[i][j];
if(mp[i][j] == 2)
sx = i,sy = j;
}
}
// dfs(sx,sy,6,0);
ans = bfs();
cout << ans;
return 0;
}
WA on #10 and #12