s[61][61],q[400];
main(x,y,i,j,f,g,_x,_y){
	for(;scanf("%d%d",&x,&y),x;){
		memset(s,0xff,sizeof(s));
		for(j=1;j<2*y;j++)
			for(i=1;i<2*x;i++)
				s[i][j]=0;
		for(j=1;j<2*y;j++)
			for(i=(j&1)?2:1;i<2*x;i+=2)scanf("%d",s[i]+j);
		q[0]=0x10001;s[1][1]=1;f=0;g=1;
		for(;f!=g;){
			_x=q[f]>>16,_y=q[f]&0xffff;f=(f+1)%400;
			if(s[_x][_y-1]==0&&s[_x][_y-2]==0)q[g]=((_x)<<16)|(_y-2),g=(g+1)%400,s[_x][_y-2]=s[_x][_y]+1;
			if(s[_x][_y+1]==0&&s[_x][_y+2]==0)q[g]=((_x)<<16)|(_y+2),g=(g+1)%400,s[_x][_y+2]=s[_x][_y]+1;
			if(s[_x-1][_y]==0&&s[_x-2][_y]==0)q[g]=((_x-2)<<16)|(_y),g=(g+1)%400,s[_x-2][_y]=s[_x][_y]+1;
			if(s[_x+1][_y]==0&&s[_x+2][_y]==0)q[g]=((_x+2)<<16)|(_y),g=(g+1)%400,s[_x+2][_y]=s[_x][_y]+1;
			if(s[2*x-1][2*y-1])break;
		}
		printf("%d\n",s[2*x-1][2*y-1]);
	}
	exit(0);
}