//problem.8
//P2802 回家
#include<iostream>
#include<queue>
using namespace std;
int a[15][15], v[15][15][10];
struct point {
int x;
int y;
int hp;
int step;
point(int a, int b, int c, int d)
{
x = a;
y = b;
hp = c;
step = d;
}
};
int sx, sy, d1x, d1y;
queue<point> r;
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };//表示 右 下 左 上
int main()
{
int n, m;
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)
{
sx = i;
sy = j;
}
if (a[i][j] == 3)
{
d1x = i;
d1y = j;
}
}
point start(sx, sy, 6, 0);
r.push(start);//入队
v[sx][sy][6] = 1;//表示状态已经经过
a[sx][sy] = 1;
int flag = 0;
while (!r.empty())
{
point current = r.front();
r.pop();
if (current.hp == 0) continue;
if (current.x == d1x && current.y == d1y)
{
flag = 1;
cout << current.step << endl;
break;
}
for (int k = 0; k <= 3; k++) {
int tx = current.x + dx[k];
int ty = current.y + dy[k];
int _hp = (a[tx][ty] == 4) ? 6 : current.hp - 1;
if (a[tx][ty] != 0 && v[tx][ty][_hp] == 0)
{
point temp(tx, ty, _hp, current.step + 1);
r.push(temp);
v[tx][ty][_hp] = 1;
}
}
}//对应while的大括号
if (flag == 0) cout << "-1" << endl;
return 0;
}