#include <stdio.h>

int map[30][30];
int W,H;

int head,tail;
typedef struct{
    int x;
    int y;
    int count;   
} step;

step queue[900];

int pop(step **next){
    if(head==tail)return 0;
    *next=&(queue[head]);
    head++;
    return 1;
}

void push(int x,int y, int count){
    queue[tail].x=x;
    queue[tail].y=y;
    queue[tail].count=count;
    tail++;
}

void clear(void){
    head=0;
    tail=0;
}

int isEmpty(void){
    if(head==tail){
        return 1;
    }
    return 0;
}

int isChecked(int x,int y){
    if(map[x][y]&16){
        return 1;
    }else{
        return 0;
    }
}

void setChecked(int x,int y){
    map[x][y]|=16;
}

int main(void){
    while(scanf("%d %d",&W,&H),W||H){
        int i,j,wall,x,y,count;
        step* next;
        for(i=0;i<30;i++){
            for(j=0;j<30;j++){
                map[i][j]=0;
            }
        }
        for(i=0;i<2*H-1;i++){
            if(i%2==0){//?¨?
                for(j=0;j<W-1;j++){
                    scanf("%d",&wall);
                    if(wall){
                        map[j][i/2]+=1;//???
                        map[j+1][i/2]+=2;//???
                    }
                }
            }else{
                for(j=0;j<W;j++){
                    scanf("%d",&wall);
                    if(wall){
                        map[j][i/2]+=4;//???
                        map[j][i/2+1]+=8;//???
                    }
                }
            }
        }        
        clear();
        push(0,0,1);
        int end=0;
        while(pop(&next)){
        //printf("head:%d tail:%d next:%p\n",head,tail,next);
            x=next->x;
            y=next->y;
            count=next->count;
            //printf("x:%d y:%d count:%d\n",x,y,count);
            if(x==W-1&&y==H-1){
                printf("%d\n",count);
                end=1;
                break;
            }
            if((map[x][y]&1)==0&&x+1<W){
                if(!isChecked(x+1,y)){
                    push(x+1,y,count+1);
                    setChecked(x+1,y);
                }
            }
            if((map[x][y]&2)==0&&x>0){
                if(!isChecked(x-1,y)){
                    push(x-1,y,count+1);
                    setChecked(x-1,y);
                }
            }
            if((map[x][y]&4)==0&&y+1<H){
                if(!isChecked(x,y+1)){
                    push(x,y+1,count+1);
                    setChecked(x,y+1);
                }
            }
            if((map[x][y]&8)==0&&y>0){
                if(!isChecked(x,y-1)){
                    push(x,y-1,count+1);
                    setChecked(x,y-1);
                }
            }
        }
        if(end==0){
            printf("%d\n",0);
        }
    }
    
    return 0;
}