#include <stdio.h>
#include <string.h>
int q[20000], top, bottom;
int map[2][60][60], visited[60][60];
int main(void)
{
    int w, h;
    while (scanf("%d%d", &w, &h), w) {
        int i, j, res;
        memset(map, 0, sizeof(map));
        memset(visited, 0, sizeof(visited));
        for(i=0;i<2*h-1;++i)
            for(j=!(i%2);j<w;++j)
                scanf("%d", &map[i%2][(i+1)/2][j]);

        if (w==1 && h==1) { puts("0"); continue; }
        top=bottom=res=0;
        visited[0][0]=1;
        q[bottom++]=0;
        while (top!=bottom) {
            int r=q[top]/100;
            int c=q[top]%100;
            int k=visited[r][c];
            ++top;
            if (r==h-1 && c==w-1) { res=visited[r][c]; break; }
            if (r+1<h && !map[1][r+1][c] && !visited[r+1][c]) {
                q[bottom++]=(r+1)*100+c;
                visited[r+1][c]=k+1;
            }
            if (r-1>=0 && !map[1][r-1][c] && !visited[r-1][c]) {
                q[bottom++]=(r-1)*100+c;
                visited[r-1][c]=k+1;
            }
            if (c+1<w && !map[0][r][c+1] && !visited[r][c+1]) {
                q[bottom++]=r*100+c+1;
                visited[r][c+1]=k+1;
            }
            if (c-1>0 && !map[0][r][c-1] && !visited[r][c-1]) {
                q[bottom++]=r*100+c-1;
                visited[r][c-1]=k+1;
            }
        }
        printf("%d\n", res);
    }
    return 0;
}