#include <stdio.h>

#define N_MAX 30
#define QUEUE_MAX 1801 /* 2*N_MAX^2 + 1 */

//Queue

int Q[QUEUE_MAX], sp, rp;

void Qstore(int N){ Q[sp++%QUEUE_MAX]=N; }
void Qstore2(int N, int M){ Q[sp++%QUEUE_MAX]=N, Q[sp++%QUEUE_MAX]=M; }
int Qretrive(){ return Q[rp++%QUEUE_MAX]; }
int Qempty(){ return sp==rp; }

//Main

int H,W;

int main(int argc, char* argv[]){
	FILE *file; file=fopen(argv[1],"r");
	int hpart[N_MAX][N_MAX], vpart[N_MAX][N_MAX], step[N_MAX][N_MAX], x, y, depth;	
		
	while(fscanf(file,"%d %d",&W,&H), W!=0){
	
		/* load */
		for(y=0; y<H-1; y++){
			for(x=0; x<W-1; x++) fscanf(file,"%d",&hpart[x][y]);
			for(x=0; x<W; x++) fscanf(file,"%d",&vpart[x][y]); }
		for(x=0; x<W-1; x++) fscanf(file,"%d",&hpart[x][y]);
		
		/* initialize */
		sp=0, rp=0;
		for(x=0; x<W; x++) for(y=0; y<H; y++) step[x][y]=-1;
		
		/* search */
		depth=0, step[0][0]=0, Qstore2(0,0), Qstore(-1);
		
		while(1){
			depth++;
			while((x=Qretrive())!=-1){
				y=Qretrive();
				if(W>x+1 && !hpart[x][y] && step[x+1][y]==-1) step[x+1][y]=depth, Qstore2(x+1,y);
				if(H>y+1 && !vpart[x][y] && step[x][y+1]==-1) step[x][y+1]=depth, Qstore2(x,y+1);
				if(x>0 && !hpart[x-1][y] && step[x-1][y]==-1) step[x-1][y]=depth, Qstore2(x-1,y);
				if(y>0 && !vpart[x][y-1] && step[x][y-1]==-1) step[x][y-1]=depth, Qstore2(x,y-1);
			}
			if(Qempty() || step[W-1][H-1]!=-1) break;
			else Qstore(-1);
		}
		
		/* out */
		if(step[W-1][H-1]==-1) printf("0\n");
		else printf("%d\n",step[W-1][H-1]+1);
	}
}