#include<bits/stdc++.h>
using namespace std;
const int dx[] = {0,1,0,-1};
const int dy[] = {-1,0,1,0};
const int M = 20;
int a[M][M];
int vis[M][M];
int n,m;
int startx,starty;
int flag = 0;
queue<int>qx;
queue<int>qy;
queue<int>qp;//步数
queue<int>qs;//血量
int bfs(){
qx.push(startx);
qy.push(starty);
qs.push(6);
qp.push(0);
while(qx.empty()){
int x = qx.front();
int y = qy.front();
int p = qp.front();
int s = qs.front();
qx.pop(),qy.pop(),qs.pop(),qp.pop();
if(a[x][y]==3){
printf("%d",p);
flag = 1;
return 0;
}
if(s>1){
for(int i=0 ; i<4 ; ++i){
int xx = x+dx[i];
int yy = y+dy[i];
if(xx>0 && xx<=n && yy>0 && yy<=m && a[xx][yy] != 0){
if(a[xx][yy] == 1 || a[xx][yy] == 3){
if(vis[xx][yy]<s-1){
vis[xx][yy] = s-1;
qs.push(xx);
qy.push(yy);
qs.push(s-1);
qp.push(p+1);
}
}
if(a[xx][yy] == 4){
if(!vis[xx][yy]){
vis[xx][yy] = 1;
qs.push(xx);
qy.push(yy);
qs.push(6);
qp.push(p+1);
}
}
}
}
}
}
}
int main(){
scanf("%d%d",&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){
startx = i;
starty = j;
}
}
}
bfs();
printf("-1");
return 0;
}