#include<bits/stdc++.h>
using namespace std;
struct node{
int x,y,xue,step;
};
queue<node> q;
char a[20][20];
int n,m;
int dx[]={1,-1,0,0};
int dy[]={0,0,-1,1};
int main(){
cin>>n>>m;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>a[i][j];
if(a[i][j]=='2'){
node s={i,j,6,0};
q.push(s);
}
}
}
while(!q.empty()){
node t=q.front();
q.pop();
if(a[t.x][t.y]=='3'){
cout<<t.step;
return 0;
}
if(t.xue==0){
cout<<-1;
return 0;
}
if(a[t.x][t.y]=='4'){
t.xue=6;
}
for(int i=0;i<4;i++){
int nx=t.x+dx[i];
int ny=t.y+dy[i];
if(a[nx][ny]!='0'&&0<=nx&&nx<n&&0<=ny&&ny<m){
node nt={nx,ny,t.xue-1,t.step+1};
q.push(nt);
}
}
}
}