//回家
#include<bits/stdc++.h>
using namespace std;
int nxt[4][2]={-1,0,1,0,0,-1,0,1};
int mat[15][15];
int book[15][15];
int xl=6,n,m,q,qq,cnt,bs,maxb=12345;
void dfs(int x,int y){
if(mat[x][y]==3){
if(bs<=maxb){
maxb=bs;
}
return ;
}
if(bs>81){
return ;
}
for(int i=0;i<4;i++){
if(bs>81){
return ;
}
int nx = x + nxt[i][0];
int ny = y + nxt[i][1];
if(xl==2){
for(int j=0;j<4;j++){
if(bs>81){
return ;
}
int nxx = x + nxt[i][0];
int nyy = y + nxt[i][1];
if(mat[nxx][nyy]==4){
xl=6;
bs++;
book[x][y]=1;
dfs(nx,ny);
book[x][y]=0;
xl=2;
bs--;
continue;
}
}
}
if(nx>=1 && nx <=n && ny>=1 && ny<=m &&xl>2&&mat[nx][ny]!=0&&book[nx][ny]==0){
xl--;
bs++;
book[x][y]=1;
dfs(nx,ny);
book[x][y]=0;
xl++;
bs--;
}
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>mat[i][j];
if(mat[i][j]==2){
q=i;
qq=j;
}
}
}
dfs(q,qq);
if(maxb==12345){
cout<<-1;
}
else{
cout<<maxb;
}
return 0;
}