#include<stdio.h>
#include<stdlib.h>

typedef struct {
  int row;
  int col;
} Coord;

typedef struct _que {
  struct _que *next;
  struct _que *prev;
  Coord point;
} *que, queelem;

typedef struct {
  que head;
  que tail;
} *queue, queueelem;

int solve (int W, int H);

queue new_queue (void);
int is_empty (queue);
int enqueue (queue, Coord);
Coord dequeue (queue);


int main () {
  int W, H;
	
	while(scanf("%d %d", &W, &H))
	{
		if(W==0&&H==0)
			break;
		else
		{
			printf("%d\n", solve(W,H));
		}
	}

  return 0;
}


int solve (int W, int H) {
  queue Q = new_queue ();
  int M[2*H+2][2*W+2], temp, temp1;
  Coord start;
  int i, j, dist, check, distcheck;
	
	
  for (i=0; i<=2*W; i++) { M[0][i] = '#'; M[2*H][i] = '#'; }
  for (i=1; i<=2*H; i++) { M[i][0] = '#'; M[i][2*W] = '#'; }
	start.row = 1;
	start.col = 1;
	
	for (i=1; i<=2*H-1; i++) {
		if(i%2!=0)
		{
			for(j=2;j<2*W;)
			{
				scanf("%d",&temp);
				if(temp==1)
					M[i][j] = '#';
				else
					M[i][j] = 0;
				M[i][j-1] = 1;
				M[i][j+1] = 1;
				j=j+2;
			}
		}
		else
		{
			for(j=1;j<2*W;)
			{
				scanf("%d",&temp);
				if(temp==1)
					M[i][j] = '#';
				else
					M[i][j] = 0;
				M[i][j+1] = '#';
				j=j+2;
			}
		}
	}
	M[2*H][2*W-1] = 'G';
	dist = 0;
	M[1][1] = 1;
	temp = 0;
	temp1 = 0;
	check = 0;
	distcheck = 1;
  enqueue(Q, start);
	while (!is_empty(Q)) {
    Coord current = dequeue(Q);
    int d;
    int D1[]={1,0,-1,0}; int D2[]={0,-1,0,1};
    for (d=0; d<4; d++) {
      Coord nc = current;
    if(M[nc.row + D1[d]][nc.col + D2[d]] == 1 || M[nc.row + D1[d]][nc.col + D2[d]] == 0)
			{
				temp = M[nc.row][nc.col];
				temp1 = M[nc.row + D1[d]][nc.col + D2[d]];
				nc.row += D1[d];
				nc.col += D2[d];
				enqueue(Q,nc);
				M[nc.row][nc.col] = temp + temp1;
				dist = temp + temp1;
			}
			else if(M[nc.row + D1[d]][nc.col + D2[d]] == 'G')
			{
			    check = 1;
			}
		}
		if(check==1)
		break;
  }
  if(check==1)
  return dist;
  else
  return 0;
}

queue new_queue (void) {
  queue q;
  q = (queue) malloc (sizeof (queueelem));
  if (q == NULL) return NULL;
  q->head = NULL;
  q->tail = NULL;
  return q;
}

int is_empty (queue q) {
  return (q && q->head == NULL);
}

int enqueue (queue q, Coord v) {
  que p;
  if (q == NULL) return 0;
  p = (que) malloc (sizeof(queelem));
  if (p == NULL) return 0;
  p->point = v;
  p->next = NULL;
  if (q->tail) {
    p->prev = q->tail;
    q->tail->next = p;
  } else {
    p->prev = NULL;
    q->head = p;
  }
  q->tail=p;
  return 1;
}

Coord dequeue (queue q) {
  que p;
  Coord v = q->head->point;
  p = q->head;
  if (p->next == NULL) {
    q->head = NULL;
    q->tail = NULL;
  } else {
    q->head = q->head->next;
    q->head->prev = NULL;
  }
  free (p);
  return v;
}