#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>

#include <functional>
#include <cassert>

typedef long long ll;
using namespace std;

#define mod 1000000007 //1e9+7
#define INF 1000000000 //1e9
#define LLINF 2000000000000000000LL //2e18
#define SIZE 30

int mm[SIZE][SIZE];
int w,h;

int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};

int dfs(int y,int x,int depth = 0){
  int ret = INF;

  if(depth >= 10) return INF;
  
  //
  for(int i=0;i<4;i++){
    int tx = x + dx[i];
    int ty = y + dy[i];
    
    if(ty<0 || h<=ty || tx<0 || w<=tx || mm[ty][tx]==1) continue;

    if(mm[ty][tx]==3) return depth+1;
    
    while(1){
      tx += dx[i];
      ty += dy[i];
      
      if(ty<0 || h<=ty || tx<0 || w<=tx) break;
      
      if(mm[ty][tx]==3) return depth+1;

      if(mm[ty][tx]==1){
	mm[ty][tx] = 0;
	ret = min(ret,dfs(ty-dy[i],tx-dx[i],depth+1));
	mm[ty][tx] = 1;
	break;
      }
    }

  }

  return ret;
}

int calc(){
  int sy,sx;
  
  for(int i=0;i<h;i++){
    for(int j=0;j<w;j++){
      scanf("%d",mm[i]+j);
      if(mm[i][j]==2){
	sy = i;
	sx = j;
      }
    }
  }

  int ans = dfs(sy,sx);
  
  if(ans==INF) ans = -1;
  
  return ans;
}

int main(){

  while(1){
    scanf("%d%d",&w,&h);
    if(w==0) break;
    printf("%d\n",calc());
  }

  
  return 0;
}
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;

queue<int>Q;
int z[100][100], x[100][100], sum; char a;

void BFS(int col,int x1,int y1) {
	Q.push(x1 * 100 + y1);
	x[x1][y1] = col;
	int a, b;
	while (!Q.empty()) {
		a = Q.front() / 100;
		b = Q.front() % 100;
		if (z[a + 1][b] == 1 && x[a + 1][b] == 0) {
			Q.push(Q.front() + 100);
			x[a + 1][b] = col;
		}
		if (z[a - 1][b] == 1 && x[a - 1][b] == 0) {
			Q.push(Q.front() - 100);
			x[a - 1][b] = col;
		}
		if (z[a][b + 1] == 1 && x[a][b + 1] == 0) {
			Q.push(Q.front() + 1);
			x[a][b + 1] = col;
		}
		if (z[a][b - 1] == 1 && x[a][b - 1] == 0) {
			Q.push(Q.front() - 1);
			x[a][b - 1] = col;
		}
		Q.pop();
	}
}

int main() {
	while (cin >> a) {
		if (a == '1') { z[1][1] = 1; }
		sum = 0;
		for (int i = 1; i <= 12; i++) {
			for (int j = 1; j <= 12; j++) {
				if (i + j != 2) {
					cin >> a; if (a == '1') { z[i][j] = 1; }
				}
			}
		}
		for (int i = 1; i <= 12; i++) {
			for (int j = 1; j <= 12; j++) {
				if (x[i][j] == 0 && z[i][j] == 1) {
					sum++;
					BFS(sum, i, j);
				}
			}
		}
		cout << sum << endl;
		memset(x, 0, sizeof(x));
		memset(z, 0, sizeof(z));
	}
}