#include <iostream>
#include <cstring>
using namespace std;
int x1, y1;
int x2, y2;
int n, m;
int min = 0x7f7f7f7f;
int G[15][15];
bool A[15][15];
int HP = 6;
int ans = 0;
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
int dfs(int x, int y, int hp, int ANS) {
hp--;
if (hp <= 0) {
return -1;
}
if (G[x][y] == 3) {
return ans;
}
if (G[x][y] == 4) {
hp = 6;
}
ans++;
for (int i = 0; i < 4; i++) {
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if (A[tx][ty] == true && tx >= 1 && tx <= n && ty >= 1 && ty <= m) {
A[tx][ty] = false;
dfs(tx, ty, hp, ans);
A[tx][ty] = true;
}
}
}
int main() {
memset(A, true, sizeof(A));
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> G[i][j];
if (G[i][j] == 0) {
A[i][j] = false;
}
if (G[i][j] == 2) {
x1 = i;
x2 = j;
}
if (G[i][j] == 3) {
x2 = i;
x2 = j;
}
}
}
cout << dfs(x1, y1, HP, ans) << endl;
return 0;
}