#include<bits/stdc++.h>
using namespace std;
const int dx[5]={0,-1,0,0,1};
const int dy[5]={0,0,-1,1,0};
struct node{
int xx;
int yy;
int step;
int ans;
};
bool b[10][10];
int n,m,ans=INT_MAX,o=6,a[10][10];
queue<node> h;
int main(){
cin>>n>>m;
int xxx,yyy;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
if(a[i][j]==2){
xxx=i;
yyy=j;
}
}
}
node t1;
t1.step=0;
t1.xx=xxx;
t1.yy=yyy;
t1.ans=0;
b[xxx][yyy]=1;
h.push(t1);
while(h.size()){
node t=h.front();
h.pop();
int tx=t.xx,ty=t.yy,tz=t.step,tzz=t.ans;
for(int i=1;i<=4;i++){
int sx=tx+dx[i],sy=ty+dy[i],sz=tz+1,szz=tzz+1;;
if(sz>=6){
break;
}
if(sx<1 || sy<1 || sx>n || sy>m || b[sx][sy]) continue;
if(a[sx][sy]==0){
b[sx][sy]=1;
continue;
}
if(a[sx][sy]==3){
cout<<szz;
return 0;
}
if(a[sx][sy]==4){
sz=0;
}
b[sx][sy]=1;
node st;
st.xx=sx;
st.yy= sy;
st.step=sz;
st.ans=szz;
h.push(st);
}
}
cout<<-1;
return 0;
}
#10#12错误 大佬请求助