#include<bits/stdc++.h>
using namespace std;
int xx[5]={0,-1,1,0,0};
int yy[5]={0,0,0,1,-1};
int ans=9999;
int n,m,sx,ex,sy,ey;
int mp[11][11],vis[11][11];
void dfs(int x,int y,int life,int step)
{
int dx,dy;
if(life<=0)
{
return;
}
if(mp[x][y]==4)
life=6;
if(x==ex&&y==ey)
{
ans=min(ans,step);
return;
}
for(int i=1;i<=4;i++)
{
dx=xx[i]+x;dy=yy[i]+y;
if(dx>=1&&dx<=n&&dy>=1&&dy<=m&&vis[dx][dy]!=1&&mp[dx][dy]!=0)
{
vis[dx][dy]=1;
dfs(dx,dy,life-1,step+1);
vis[dx][dy]=0;
}
}
}
int main()
{
//freopen("text.in","r",stdin);
//freopen("text.out","w",stdout);
scanf("%d %d\n",&n,&m);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%d ",&mp[i][j]);
if(mp[i][j]==2)
{
sx=i;sy=j;
}
if(mp[i][j]==3)
{
ex=i;ey=j;
}
}
scanf("\n");
}
dfs(sx,sy,6,0);
if(ans!=9999)
printf("%d",ans);
else
printf("-1");
return 0;
}