#include <stdio.h>

int main(void) {
    int w, h, i, j, maze[65][65], W[65][65], a, min;
    while (1) {
        scanf("%d %d", &w, &h);
        if (w==0 && h==0) break;
        
        for (i=1; i<=2*w+1; i++) maze[1][i]=100000;
        for (i=1; i<=2*w+1; i++) maze[2*h+1][i]=100000;
        for (i=1; i<=2*h+1; i++) maze[i][1]=100000;
        for (i=1; i<=2*h+1; i++) maze[i][2*w+1]=100000;
        
        for (i=2; i<=2*h; i++) {
            for (j=2; j<=2*w; j++) {
                if (i%2==1 && j%2==1) maze[i][j]=100000;
                else maze[i][j]=0;
            }
        }
        
        for (i=1; i<=2*h-1; i++) {
            if (i%2==1) {
                for (j=1; j<=w-1; j++) {
                    scanf("%d", &W[i][j]);
                    maze[i+1][2*j+1]=100000*W[i][j];
                }
            }
            else {
                for (j=1; j<=w; j++) {
                    scanf("%d", &W[i][j]);
                    maze[i+1][2*j]=100000*W[i][j];
                }
            }
        }
        maze[2][2]=1;
        
        a=1;
        while (a==1) {
            a=0;
            for (i=2; i<=2*h; i++) {
                for (j=2; j<=2*w; j++) {
                    min=100000;
                    if (maze[i-1][j]<min && maze[i-1][j]!=0) min=maze[i-1][j];
                    if (maze[i][j-1]<min && maze[i][j-1]!=0) min=maze[i][j-1];
                    if (maze[i][j+1]<min && maze[i][j+1]!=0) min=maze[i][j+1];
                    if (maze[i+1][j]<min && maze[i+1][j]!=0) min=maze[i+1][j];
                    if (min!=100000 && (maze[i][j]==0 && maze[i][j]!=100000)) {
                        maze[i][j]=min+1;
                        a=1;
                    }
                }
            }
        }

        printf("%d\n", (maze[2*h][2*w]+1)/2);
    }
    return 0;
}
