#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m;
int a[10][10];
int sx,sy;
int f[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int ans,hx,hy;
int book[10][10];
struct s{
int x,y,l,t;
};
queue<s> q;
s ms(int x,int y,int l,int t){
s a;
a.l=l;
a.t=t;
a.x=x;
a.y=y;
return a;
}
void bfs(){
while(!q.empty()){
if(q.front().x==hx && q.front().y==hy){
cout << q.front().t;
return;
}
for(int i=0;i<4;i++){
int newx=f[i][0]+q.front().x;
int newy=f[i][1]+q.front().y;
int newlife;
if(a[newx][newy]==4){
newlife=6;
}else newlife=q.front().l-1;
if(newlife>0&&newx>0&&newy>0&&newx<=n&&newy<=m&&book[newx][newy]<newlife&&a[newx][newy]!=0){
q.push(ms(newx,newy,newlife,q.front().t+1));
book[newx][newy]=newlife;
}
}
q.pop();
}
cout << -1;
return;
}
signed main(){
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){
sx=i;
sy=j;
}else if(a[i][j]==3){
hx=i;
hy=j;
}
}
}
q.push(ms(sx,sy,6,0));
book[sx][sy]=6;
bfs();
return 0;
}