#include <stdio.h>
#include <string.h>
int wall[32][32];
int distance[32][32];
int w, h;

int main (void){
	int i, j, foo;
	scanf("%d %d", &w, &h);
	while (w && h){
		memset(wall, 0, sizeof(wall));
		memset(distance, w*h, sizeof(distance));
		for (i=0; i<h-1; i++){
			for (j=0; j<w-1; j++){
				scanf("%d", &foo);
				wall[j][i] += foo;
			}
			for (j=0; j<w; j++){
				scanf("%d", &foo);
				wall[j][i] += foo * 2;
			}
		}
		for (j=0; j<w-1; j++){
				scanf("%d", &foo);
				wall[j][i] += foo;
		}
		distance[0][0] = 1;
		go(0, 0);
		if (distance[w-1][h-1] < w*h) printf("%d\n", distance[w-1][h-1]);
		else printf("0\n");
		scanf("%d %d", &w, &h);
	}
}

void go(int x, int y){
	if (y < h-1 && !(wall[x][y] & 2) && distance[x][y+1] > distance[x][y] + 1){
		distance[x][y+1] = distance[x][y] + 1;
		go(x, y+1);
	}
	if (x < w-1 && !(wall[x][y] & 1) && distance[x+1][y] > distance[x][y] + 1){
		distance[x+1][y] = distance[x][y] + 1;
		go(x+1, y);
	}
	if (y && !(wall[x][y-1] & 2) && distance[x][y-1] > distance[x][y] + 1){
		distance[x][y-1] = distance[x][y] + 1;
		go(x, y-1);
	}
	if (x && !(wall[x][y-1] & 1) && distance[x-1][y] > distance[x][y] + 1){
		distance[x-1][y] = distance[x][y] + 1;
		go(x-1, y);
	}

}