#include<bits/stdc++.h>
using namespace std;
int mp[100][100],sx,sy,fx,fy,t = 0,n,m,cx,cy,xe = 6;
bool vist[100][100];
int ax[6]={-1,0,1,0};
int ay[6]={0,1,0,-1};
void mg(int nx,int ny){
int i;
xe--;
t++;
cout << xe << endl;
if(mp[nx][ny] == 3)return;
for(i = 0;i < 4; ++ i){
int tx,ty;
tx = nx + ax[i];
ty = ny + ay[i];
if(mp[tx][ty] == 0 || vist[tx][ty] == 1)continue;
if(tx <= 0 || tx > n || ty <= 0 || ty > m)continue;
if(mp[nx][ny] == 4) xe = 6;
vist[tx][ty] = 1;
if(xe == 0) return;
mg(tx,ty);
}
}
int main(){
int i;
cin >> n >> m;
for (i = 1;i <= n; ++ i){
for(int j =1;j <= m; ++ j)
cin>>mp[i][j];
}
for (i = 1;i <= n; ++ i){
for(int j =1;j <= m; ++ j)
if(mp[i][j] != 0 && vist[i][j] == 0)mg(i,j);
}
if(xe > 0)cout << t;
else cout << -1;
return 0;
}