#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100000000
int W,H,G[32][32][4],r,t,i,j,Q[MAX][3],f,e,mc[32][32];
int mh[4]={0,1,0,-1},mw[4]={1,0,-1,0};
int main()
{
	for(;scanf("%d%d",&W,&H),W;)
	{
		memset(G,0,sizeof(G));
		memset(mc,-1,sizeof(mc));
		for(i=0;i<2*H-1;i++)
			for(j=0;j<W-1+(i%2);j++)
			{
				scanf("%d",&t);
				if(!t)G[i/2][j][i%2]=G[i/2+i%2][j+(!(i%2))][i%2+2]=1;
			}
		for(f=r=Q[0][0]=Q[0][1]=0,Q[0][2]=e=1;f<e;f++)
		{
			int nh=Q[f][0],nw=Q[f][1],nc=Q[f][2];
			if(f==MAX-1)
				break;
			if(nc>H*W||(mc[nh][nw]!=-1&&mc[nh][nw]<=nc))
				continue;
			if(nh==H-1&&nw==W-1)
			{
				r=nc;break;
			}
			for(i=0;i<4;i++)
				if(G[nh][nw][i])
				{
					if(mc[nh][nw]!=-1||mc[nh+mh[i]][nw+mw[i]]>=nc+1)
						continue;
					Q[e][0]=nh+mh[i];
					Q[e][1]=nw+mw[i];
					Q[e][2]=mc[nh][nw]=nc+1;
					e++;
				}
		}
		printf("%d\n",r);
	}
	return 0;
}