#include <stdio.h>
#define ll long long
#define rep(i,l,r)for(ll i=l;i<r;i++)

int d[99][99];
int que[1000],quecnt;
int d4[]={0,2,0,-2,0};

int main(){
	ll w,h;
	while(scanf("%lld%lld",&w,&h),w){
		rep(i,0,2*h)rep(j,0,2*w)d[i][j]=0;
		rep(i,0,h){
			rep(j,0,w-1)scanf("%lld",&d[2*i][2*j+1]);
			if(i!=h-1)rep(j,0,w)scanf("%lld",&d[2*i+1][2*j]);
		}
		int flag=0;
		d[0][0]=1;
		que[0]=0;
		quecnt=1;
		rep(i,0,quecnt){
			ll x=que[i]/100;
			ll y=que[i]%100;
			if(x==2*(h-1)&&y==2*(w-1)){
				printf("%lld\n",d[x][y]);
				flag=1;
				break;
			}
			rep(k,0,4){
				ll xx=x+d4[k  ];
				ll yy=y+d4[k+1];
				ll xxt=x+d4[k  ]/2;
				ll yyt=y+d4[k+1]/2;
				if(0<=xx&&xx<2*h&&0<=yy&&yy<2*w&&!d[xx][yy]&&!d[xxt][yyt]){
					d[xx][yy]=d[x][y]+1;
					que[quecnt++]=xx*100+yy;
				}
			}
		}
		if(!flag)puts("0");
	}
}
