#include<bits/stdc++.h>
using namespace std;
int n,m,sx,sy,fx,fy;
char mat[15][15];
int nxt[4][2]={0,1,0,-1,1,0,-1,0};
int book[15][15];
struct node{
int x,y,cost,hp;
friend bool operator < (node a,node b){
return a.cost>b.cost;
}
};
priority_queue<node>q;
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')
sx=i,sy=j;
if(mat[i][j]=='3')
fx=i,fy=j;
}
}
memset(book,0,sizeof(book));
book[sx][sy]=1;
q.push({sx,sy,0,6});
while(!q.empty()){
node tmp=q.top();
q.pop();
if(tmp.x==fx && tmp.y==fy){
cout<<tmp.cost<<endl;
return 0;
}
if(tmp.hp>1){
for(int i=0;i<4;i++){
int nx=nxt[i][0]+tmp.x;
int ny=nxt[i][1]+tmp.y;
if(nx>=1 && nx<=n && ny>=1 && ny<=m){
if(mat[nx][ny]=='1' || mat[nx][ny]=='3') {
if(book[nx][ny]<tmp.hp-1){
book[nx][ny]=tmp.hp-1;
q.push({nx,ny,tmp.cost+1,tmp.hp-1});
}
}
if(mat[nx][ny]==4){
if(!book[nx][ny]){
book[nx][ny]=1;
q.push({nx,ny,tmp.cost+1,6});
}
}
}
}
}
}
cout<<-1<<endl;
return 0;
}