#include<bits/stdc++.h>
using namespace std;
int n,m,a[10][10],b[10][10],mn = 1000000000,t;
bool k = 0;
int c_x,c_y,f_x,f_y;
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
queue<int>q;
void bfs(int x,int y){
q.push(x);
q.push(y);
q.push(0);
while(q.size()){
x = q.front();
q.pop();
y = q.front();
q.pop();
t = q.front();
q.pop();
if(a[x][y] == 4) b[x][y] = 6;
if(x == f_x && y == f_y){
cout << t;
k = 1;
return;
}
for(int i = 0;i < 4;i ++){
int xx = x + dx[i];
int yy = y + dy[i];
if(x < 1 || x > n || y < 1 || y > m || a[x][y] == 0) continue;
if(b[x][y] - 1 > b[xx][yy]){
b[xx][yy] = b[x][y] - 1;
q.push(xx);
q.push(yy);
q.push(t + 1);
}
}
}
}
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] == 3){
f_x = i;
f_y = j;
}
if(a[i][j] == 2){
c_x = i;
c_y = j;
}
}
}
b[c_x][c_y] = 6;
bfs(c_x,c_y);
if(k == 0) cout << -1;
return 0;
}