#include <bits/stdc++.h>
using namespace std;
int n, m, a[15][15], ans;
bool vis[15][15];
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {1, -1, 0, 0};
bool ok = false;
void dfs(int x, int y, int hp, int step)
{
if (x < 1 || y < 1 || x > n || y > m || hp == 0 || a[x][y] == 0)
{
return;
}
if (a[x][y] == 3)
{
ok = true;
ans = step;
return;
}
if (a[x][y] == 4)
{
hp = 6;
}
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
dfs(xx, yy, hp - 1, step + 1);
}
}
int main()
{
cin >> n >> m;
int ii, jj, iii;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> a[i][j];
if (a[i][j] == 2)
{
ii = i;
jj = j;
}
}
}
dfs(ii, jj, 6, 0);
if (!ok)
{
cout << -1;
return 0;
}
cout << ans;
return 0;
}