#include<bits/stdc++.h>
using namespace std;
struct fsx{
int x,y,s,xl;
}st,fr,nt,ed;
queue <fsx> q;
int n,m,b[10][10],mp[10][10],ne[4][2]={1,0,0,1,-1,0,0,-1};
void bfs()
{
while(!q.empty())
{
fr=q.front();
q.pop();
for(int i=0;i<4;i++)
{
nt.x=fr.x+ne[i][0];
nt.y=fr.y+ne[i][1];
nt.s=fr.s+1;
if(mp[nt.x][nt.y]==4) nt.xl=6;
else nt.xl=fr.xl-1;
if(mp[nt.x][nt.y]!=0&&b[nt.x][nt.y]==0&&nt.x<n&&nt.y<m&&nt.x>=0&&nt.y>=0&&nt.xl>0)
{
if(mp[nt.x][nt.y]==3)
{
cout<<nt.s;
return;
}
q.push(nt);
b[nt.x][nt.y]=1;
}
}
}
cout<<-1;
}
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>mp[i][j];
if(mp[i][j]==2)
{
st.x=i;
st.y=j;
st.xl=6;
b[i][j]=1;
q.push(st);
}
if(mp[i][j]==3)
{
ed.x=i;
ed.y=j;
}
}
}
bfs();
return 0;
}