import std.algorithm;
import std.conv;
import std.exception;
import std.stdio;
import std.string;
import std.typecons;
 
struct Queue(T){
    T[900] content;
    size_t head;
    size_t tail;

    T front(){
        enforce(head != tail);
        return content[head];
    }

    void popFront(){
        enforce(head != tail);
        ++head;
    }

    void pushBack(T value){
        content[tail] = value;
        ++tail;
    }

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

    size_t length(){
        return tail - head;
    }
}

void main(){
    bool[900][900] M;
    Queue!int queue;
    int[900] d;
    while(true){
        auto input = readln.split;
        if(input[0] == "0" && input[1] == "0"){
            break;
        }
        int w = input[0].to!int;
        int h = input[1].to!int;

        foreach(i; 0..h){
            {
                auto line = readln.split;
                foreach(j; 0..w - 1){
                    if(line[j] == "0"){
                        M[i * w + j][i * w + j + 1] = true;
                        M[i * w + j + 1][i * w + j] = true;
                    }else{
                        M[i * w + j][i * w + j + 1] = false;
                        M[i * w + j + 1][i * w + j] = false;
                    }
                }
            }
            {
                if(i == h - 1){
                    break;
                }
                auto line = readln.split;
                foreach(j; 0..w){
                    if(line[j] == "0"){
                        M[i * w + j][(i + 1) * w + j] = true;
                        M[(i + 1) * w + j][i * w + j] = true;
                    }else{
                        M[i * w + j][(i + 1) * w + j] = false;
                        M[(i + 1) * w + j][i * w + j] = false;
                    }
                }
            }
        }

        d[1..w * h] = 0;
        d[0] = 1;

        queue.clear;
        queue.pushBack(0);

        while(queue.length){
            int v = queue.front;
            queue.popFront;
            if(v - w >= 0 && M[v][v - w] && !d[v - w]){
                d[v - w] = d[v] + 1;
                queue.pushBack(v - w);
            }
            if(v % w + 1 < w && M[v][v + 1] && !d[v + 1]){
                d[v + 1] = d[v] + 1;
                queue.pushBack(v + 1);
            }
            if(v + w < w * h && M[v][v + w] && !d[v + w]){
                d[v + w] = d[v] + 1;
                queue.pushBack(v + w);
            }
            if(v % w - 1 >= 0 && M[v][v - 1] && !d[v - 1]){
                d[v - 1] = d[v] + 1;
                queue.pushBack(v - 1);
            }
        }
        d[w * h - 1].writeln;
    }
}