// Aizu 1166: Amazing Mazes
// 2017.9.14 bal4u@uu

#include <stdio.h>
#include <string.h>

#define QMAX 2000
#define N 1
#define E 2
#define S 4
#define W 8

typedef struct { int r, c; } Q;
Q que[QMAX+3]; int top, end;
char map[33][33], mk[33][33];
int w, h;
int m[4][4] = { { -1,0,N,S }, { 0,1,E,W }, { 1,0,S,N }, { 0,-1,W,E } }; 

int main()
{
	int i, r, c, r2, c2, tt, ans;

	while(scanf("%d%d", &w, &h) && w) {
		memset(mk, 0, sizeof(mk)), memset(map, 0, sizeof(map));
		for (r = 0; ; r++) {
			int a;
			for (c = 1; c < w; c++) { scanf("%d", &a); if (a) map[r][c-1] |= E, map[r][c] |= W; }
			if (r >= h-1) break;
			for (c = 0; c < w; c++) { scanf("%d", &a); if (a) map[r][c] |= S, map[r+1][c] |= N; }
		}
		ans = 0, tt = 1, que[0].r = que[0].c = 0, que[1].r = -1, top = 0, end = 2;
		while (top < end) {
			r = que[top].r, c = que[top++].c;
			if (r == h-1 && c == w-1) { ans = tt; break; }
			if (r < 0) { tt++, que[end].r = -1; if (++end >= QMAX) end = 0; continue; }
			for (i = 0; i < 4; i++) {
				r2 = r + m[i][0], c2 = c + m[i][1];
				if (r2 < 0 || r2 >= h || c2 < 0 || c2 >= w) continue;
				if ((map[r][c] & m[i][2]) || (map[r2][c2] & m[i][3])) continue;
				if (mk[r2][c2]) continue;
				mk[r2][c2] = 1;
				que[end].r = r2, que[end++].c = c2;
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}