#include<iostream>
#include<stdio.h>
#include<string>
#include<stdio.h>
#include<vector>
#include<unordered_map>
#include<map>
#include<math.h>
#include<queue>
#include<string.h>
#include<string>
#include<list>
#include<set>
#include<queue>
#include<algorithm>
using namespace std;
#define ll long long
#define pll pair<ll,ll>
typedef pair<int, int> pii;
bool b[120][7];
int a[10][10],n,m,cnt=0,x,y;
queue<pair<pii,pii> >q;
int z[5][3] = { {1,0},{-1,0},{0,1},{0,-1} };
bool check(int px,int py) {
if (px<1 || px>n)return false;
if (py<1 || py>m) return false;
return true;
}
void bfs(int x, int y) {
q.push({ {x,y},{6,0} });
while (!q.empty()) {
pair<pii,pii> p = q.front(); q.pop();
int px = p.first.first, py = p.first.second,pp=p.second.first,cnt=p.second.second;
if (a[px][py] == 3) { cout << cnt; exit(0); }
if (a[px][py] == 4) pp = 6;
for(int i=0;i<4;++i) {
int ppx = px + z[i][0], ppy = py + z[i][1];
if (!b[ppx * 10 + ppy][pp - 1] && pp > 1&&a[ppx][ppy]!=0&&check(ppx,ppy)){
q.push({ {px + z[i][0],py + z[i][1]},{pp - 1,cnt + 1} });
b[(px + z[i][0]) * 10 + py + z[i][1]][pp - 1] = true;
}
}
}
}
int main() {
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) x = i, y = j;
}
bfs(x, y);
cout << -1;
return 0;
}
pair的无限套娃,哈哈哈