#include<bits/stdc++.h>
using namespace std;
const int M = 20;
const int dx[] = {0,1,0,-1};
const int dy[] = {-1,0,1,0};
int a[M][M];
int n,m;
int blood=6;
queue<int>qx;
queue<int>qy;
queue<int>qs;
int bfs(int x,int y){
qx.push(x);
qy.push(y);
qs.push(0);
int fx = qx.front();
int fy = qy.front();
int fs = qs.front();
qx.pop();
qy.pop();
qs.pop();
while(!qx.empty()){
for(int i=0 ; i<4 ; i++){
int xx = x+dx[i];
int yy = y+dy[i];
if(xx>0 && xx<=n && yy>0 && yy<=m && a[xx][yy]!=0 && blood>0){
qx.push(xx);
qy.push(yy);
if(blood == 0 || fs>m*n){
printf("%d",-1);
return 0;
}
if(a[xx][yy]==1 || a[xx][yy]==2){
qs.push(fs+1);
blood--;
}
else if(a[xx][yy]==3 && blood!=0){
printf("%d",fs);
return 0;
}
else if(a[xx][yy]==4 && blood!=0){
qs.push(fs+1);
blood=6;
}
else if(a[xx][yy]==4 && blood==0){
printf("%d",-1);
return 0;
}
}
else{
printf("%d",-1);
return 0;
}
}
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1 ; i<=n ; i++){
for(int j=1 ; j<=m ; j++){
scanf("%d",&a[i][j]);
}
}
for(int i=1 ; i<=n ; i++){
for(int j=1 ; j<=m ; j++){
if(a[i][j] == 2){
printf("%d",bfs(i,j));
}
}
}
return 0;
}