#include <bits/stdc++.h>
#define begin front
using namespace std;
int n,m,a[11][11],sx,sy,b[11][11];
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
struct node{
int step,x,y,t;
} s;
queue<node> t;
int main ()
{
ios::sync_with_stdio (false);
cin.tie (0);
cout.tie (0);
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) s.x=i,s.y=j;
if (a[i][j]==3) sx=i,sy=j;
}
b[s.x][s.y]=1;
t.push (s);
while (!t.empty ())
{
node w;
w.step=t.begin ().step;
w.x=t.begin ().x;
w.y=t.begin ().y;
w.t=t.begin ().t;
if (w.x==sx&&w.y==sy)
{
cout<<w.step<<endl;
return 0;
}
for (int i=0;i<4;i++)
{
int tx=w.x+dx[i],ty=w.y+dy[i],s=w.t;
if (tx>0&&tx<=n&&ty>0&&ty<=m)
if (a[tx][ty]!=0&&b[tx][ty]!=1)
{
if (a[tx][ty]==4) w.t=6;
node q;
q.step=w.step+1;
q.t=w.t-1;
q.x=tx;
q.y=ty;
b[tx][ty]=1;
t.push (q);
}
t.pop ();
}
}
cout<<-1<<endl;
return 0;
}