#include<bits/stdc++.h>
using namespace std;
struct re{
int x,y,z,s;
};
queue<re> q;
int n,m;
int a[10][10];
int fx[5]={0,1,-1,0,0};
int fy[5]={0,0,0,1,-1};
bool vis[10][10];
int main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
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){
q.push((re){i,j,0,6});
}
}
}
while(!q.empty()){
re x=q.front();
q.pop();
for(int i=1;i<=4;i++){
int tx=x.x+fx[i];
int ty=x.y+fy[i];
if(a[tx][ty]==0) continue;
if(tx>=1&&ty>=1&&tx<=n&&ty<=m&&x.s>1&&!vis[tx][ty]){
if(a[tx][ty]==1&&x.s>1){
q.push((re){tx,ty,x.z+1,x.s-1});
vis[tx][ty]=true;
}
if(a[tx][ty]==4&&x.s>1){
q.push((re){tx,ty,x.z+1,6});
vis[tx][ty]=true;
}
if(a[tx][ty]==3&&x.s>1){
cout<<x.z+1;
return 0;
}
}
}
}
cout<<-1;
}