#include <stdio.h>
#define rep(i,n) for(int i=0; i<(int)(n); i++)

int W, H;
int a[101][101];
int cnt[101][101];
typedef struct{int x; int y;} P;
P que[10101];
int qf, qb;

int solve() {
    int ans = 0;
    rep(i, H) rep(j, W) cnt[i][j] = -1;
    qb = 0; qf = 0;
    cnt[0][0] = 1;
    que[qb].x = 0, que[qb++].y = 0;
    while(qb-qf > 0) {
        int cx = que[qf].x, cy = que[qf++].y;
        int nx = cx + 1, ny = cy;
        if(nx < H) {
             if(cnt[nx][ny] == -1 && a[2*cx+1][cy] == 0) {
                cnt[nx][ny] = cnt[cx][cy] + 1;
                que[qb].x = nx; que[qb++].y = ny;
            }
        }
        nx = cx - 1, ny = cy;
        if(nx >= 0) {
             if(cnt[nx][ny] == -1 && a[2*cx-1][cy] == 0) {
                cnt[nx][ny] = cnt[cx][cy] + 1;
                que[qb].x = nx; que[qb++].y = ny;
            }
        }
        nx = cx, ny = cy + 1;
        if(ny < W) {
             if(cnt[nx][ny] == -1 && a[2*cx][cy] == 0) {
                cnt[nx][ny] = cnt[cx][cy] + 1;
                que[qb].x = nx; que[qb++].y = ny;
            }
        }
        nx = cx, ny = cy - 1;
        if(ny >= 0) {
             if(cnt[nx][ny] == -1 && a[2*cx][cy-1] == 0) {
                cnt[nx][ny] = cnt[cx][cy] + 1;
                que[qb].x = nx; que[qb++].y = ny;
            }
        }
    }
    ans = (cnt[H-1][W-1] != -1 ? cnt[H-1][W-1] : 0);
    return ans;
}

int main(){
    while(1) {
        scanf("%d%d", &W, &H);
        if(W == 0 && H == 0) break;
        rep(i, 2*H-1){
            rep(j, W - ((i+1)%2)) {
                scanf("%d", &a[i][j]);
            }
        }
        printf("%d\n", solve());
    }
}
