Go: package main

import (
	"bufio"
	"container/list"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	io := NewIo()
	defer io.Flush()
	for {
		w, h := io.NextInt(), io.NextInt()
		if w == 0 {
			break
		}
		xWall := make([][]int, h)
		yWall := make([][]int, h)
		for i := 0; i < h; i++ {
			xWall[i], yWall[i] = make([]int, w), make([]int, w)
			for j := 0; j < w; j++ {
				xWall[i][j], yWall[i][j] = -1, -1
			}
		}
		for i := 0; i < h*2-1; i++ {
			if i%2 == 0 {
				for j := 0; j < w-1; j++ {
					xWall[i/2][j] = io.NextInt()
				}
			} else {
				for j := 0; j < w; j++ {
					yWall[i/2][j] = io.NextInt()
				}
			}
		}
		//io.Println(bfs(w, h, xWall, yWall))
		fmt.Println(bfs(w, h, xWall, yWall))
	}
}

type P struct {
	x, y int
}

func bfs(w, h int, x, y [][]int) int {
	d := make([][]int, h)
	for i := 0; i < h; i++ {
		d[i] = make([]int, w)
	}
	q := list.New()
	q.PushBack(P{0, 0})
	d[0][0] = 1

	for q.Len() != 0 {
		pos := q.Remove(q.Front()).(P)
		if pos.x == w-1 && pos.y == h-1 {
			break
		}
		if pos.x > 0 && x[pos.y][pos.x-1] == 0 && d[pos.y][pos.x-1] == 0 {
			d[pos.y][pos.x-1] = d[pos.y][pos.x] + 1
			q.PushBack(P{pos.x - 1, pos.y})
		}
		if pos.x < w-1 && x[pos.y][pos.x] == 0 && d[pos.y][pos.x+1] == 0 {
			d[pos.y][pos.x+1] = d[pos.y][pos.x] + 1
			q.PushBack(P{pos.x + 1, pos.y})
		}
		if pos.y > 0 && y[pos.y-1][pos.x] == 0 && d[pos.y-1][pos.x] == 0 {
			d[pos.y-1][pos.x] = d[pos.y][pos.x] + 1
			q.PushBack(P{pos.x, pos.y - 1})
		}
		if pos.y < h-1 && y[pos.y][pos.x] == 0 && d[pos.y+1][pos.x] == 0 {
			d[pos.y+1][pos.x] = d[pos.y][pos.x] + 1
			q.PushBack(P{pos.x, pos.y + 1})
		}
	}
	return d[h-1][w-1]
}

// I/O template
type Io struct {
	reader    *bufio.Reader
	writer    *bufio.Writer
	tokens    []string
	nextToken int
}

func NewIo() *Io {
	return &Io{
		reader: bufio.NewReader(os.Stdin),
		writer: bufio.NewWriter(os.Stdout),
	}
}

func (io *Io) Flush() {
	err := io.writer.Flush()
	if err != nil {
		panic(err)
	}
}

func (io *Io) NextLine() string {
	var buff []byte
	for {
		line, isPrefix, err := io.reader.ReadLine()
		if err != nil {
			panic(err)
		}
		buff = append(buff, line...)
		if !isPrefix {
			break
		}
	}
	return string(buff)
}

func (io *Io) Next() string {
	for io.nextToken >= len(io.tokens) {
		line := io.NextLine()
		io.tokens = strings.Fields(line)
		io.nextToken = 0
	}
	s := io.tokens[io.nextToken]
	io.nextToken++
	return s
}

func (io *Io) NextInt() int {
	i, err := strconv.Atoi(io.Next())
	if err != nil {
		panic(err)
	}
	return i
}

func (io *Io) NextFloat() float64 {
	i, err := strconv.ParseFloat(io.Next(), 64)
	if err != nil {
		panic(err)
	}
	return i
}

func (io *Io) Println(a ...interface{}) {
	fmt.Fprintln(io.writer, a...)
}

func (io *Io) Printf(format string, a ...interface{}) {
	fmt.Fprintf(io.writer, format, a...)
}

func (io *Io) PrintIntSlice(a []int) {
	b := []interface{}{}
	for _, x := range a {
		b = append(b, x)
	}
	io.Println(b...)
}

func (io *Io) PrintStringSlice(a []string) {
	b := []interface{}{}
	for _, x := range a {
		b = append(b, x)
	}
	io.Println(b...)
}

func Log(name string, value interface{}) {
	fmt.Fprintf(os.Stderr, "%s=%+v\n", name, value)
}

func ExampleIo() {
	io := NewIo()
	defer io.Flush()
	a := make([]int, 0, 3)
	a[0], a[1], a[2] = io.NextInt(), io.NextInt(), io.NextInt()
	io.Println(a)
	io.PrintIntSlice(a)
	Log("io", a)
}

C++: #include <bits/stdc++.h>
#define REP(i, n) for(int i = 0; (i) < (n); (i)++)
using namespace std;

struct Edge{
    int to;
    long weight;
    Edge(int t, long w) : to(t), weight(w) {}
};

long modpow(long a, long n, long mod) {
    long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}

// a^{-1} mod を計算する
long modinv(long a, long mod) {
    return modpow(a, mod - 2, mod);
}

struct compare1 { 
    bool operator()(const pair<long, long>& value,  
                                const long& key) 
    { 
        return (value.first < key); 
    } 
    bool operator()(const long& key,  
                    const pair<long, long>& value) 
    { 
        return (key < value.first); 
    } 
};

struct RMQ {
    vector<int> a;
    int inf = 2000000000; // 2*10^9
    int n = 1;

    RMQ(int n_ = 1){
        init(n_);
    }

    void init(int n_ = 1){
        while(n < n_) n *= 2;
        a.resize(2*n-1);
        REP(i, 2*n-1) a[i] = inf;
    }
    //k番目の値(0-indexed)をbに変更
    void update(int k, int b){
        k += n-1;
        a[k] = b;
        while(k > 0){
            k = (k-1)/2;
            a[k] = min(a[2*k+1], a[2*k+2]);
        }
    }
    //[c,b)の最小値を返す際に呼ぶ関数
    int query_first(int c, int b){
        return query(c, b, 0, 0, n);
    }
    //k : 節点番号, l, rはその接点が[l, r)に対応することを示す
    int query(int c, int b, int k, int l, int r){
        if(r <= c || b <= l) return inf;
        if(c <= l && r <= b) return a[k];
        else{
            int vl = query(c, b, k*2+1, l, (l+r)/2);
            int vr = query(c, b, k*2+2, (l+r)/2, r);
            return min(vl, vr);
        }
    }
};

struct UnionFind {
    vector<int> par;
    vector<int> rank;

    UnionFind(int n = 1){
        init(n);
    }

    void init(int n = 1){
        par.resize(n);
        rank.resize(n);
        REP(i, n) par[i] = i, rank[i] = 0; 
    }

    int root(int x){
        if(par[x] == x) return x;
        else return par[x] = root(par[x]);
    }

    bool issame(int x, int y){
        return root(x) == root(y);
    }

    bool merge(int x, int y){
        x = root(x); y = root(y);
        if(x == y) return false;
        if(rank[x] < rank[y]) swap(x, y);
        if(rank[x] == rank[y]) rank[x]++;
        par[y] = x;
        return true;
    }
};

template<class Abel> struct weightedUnionFind{
    vector<int> par;
    vector<int> rank;
    vector<Abel> diff_weight;

    weightedUnionFind(int n = 1, Abel SUM_UNITY = 0){
        init(n, SUM_UNITY);
    }

    void init(int n = 1, Abel SUM_UNITY = 0){
        par.resize(n); rank.resize(n); diff_weight.resize(n);
        REP(i, n) par[i] = i, rank[i] = 0, diff_weight[i] = SUM_UNITY; 
    }

    int root(int x){
        if(par[x] == x) return x;
        else{
            int r = root(par[x]);
            diff_weight[x] += diff_weight[par[x]];
            return par[x] = r;
        }
    }

    Abel weight(int x){
        root(x);
        return diff_weight[x];
    }

    bool issame(int x, int y){
        return root(x) == root(y);
    }

    bool merge(int x, int y, Abel w){
        w += weight(x); w -= weight(y);
        x = root(x); y = root(y);
        if(x == y) return false;
        if(rank[x] < rank[y]) swap(x, y), w = -w;
        if(rank[x] == rank[y]) rank[x]++;
        par[y] = x;
        diff_weight[y] = w;
        return true;
    }

    Abel diff(int x, int y){
        return weight(y) - weight(x);
    }
};

using Graph = vector<vector<int>>;
using P = pair<int, int>;

/*
void dijkstra(int s, int V, Graph &G, long* d){
    priority_queue<P, vector<P>, greater<P>> pque;
    fill(d, d + V, INF);
    d[s] = 0;
    pque.push(P(0, s));

    while(!pque.empty()){
        P p = pque.top(); pque.pop();
        int now = p.second;
        if(d[now] < p.first) continue;
        REP(i, G[now].size()){
            Edge e = G[now][i];
            if(d[e.to] > d[now] + e.weight){
                d[e.to] = d[now] + e.weight;
                pque.push(P(d[e.to], e.to));
            }
        }
    }
}
*/

int GCD(int a, int b){
    if(b == 0) return a; 
    if(a < b) return GCD(b, a);
    else return GCD(b, a%b);
}

struct BIT{
    vector<long> dat;
    int n = 1;

    BIT(int nn = 1){
        init(nn);
    }

    void init(int nn = 1){
        while(n < nn) n *= 2;
        dat.resize(n+1);
        REP(i, n+1) dat[i] = 0l;
    }
    //1-indexed!!!!
    //index iにx加える
    void add(int i, long x){
        while(i <= n){
            dat[i] += x;
            i += (i&(-i));
        }
    }
    //1-indexed!!!!!
    //index 1-iまでの和を求める
    long get_sum(int i){
        long ans = 0l;
        while(i > 0){
            ans += dat[i];
            i -= (i & (-i));
        }
        return ans;
    }
};

//{0, 1, 2, ..., n-1}までの中からk個の要素を持つ部分集合についての処理を行う
int next_combination(int sub){
    int x = sub & -sub, y = sub + x;
    return (((sub & ~y) / x) >> 1) | y;
}
//main関数内で
//bit = (1<<k)-1;
//for(; bit < (1<<n); bit = next_combination(bit))
// REP(i, n) if(bit & (1<<i)) でbitの中で選ばれている要素iを全部取得できる
//bitset<8>(bit)でbitを8桁の2進数で表示できる

int main()
{
    for(;;){
        int w, h; cin >> w >> h;
        if(w==0 && h==0) break;
        int tate[40][40], yoko[40][40];
        REP(i, 2*h-1){
            if(i%2==0){
                REP(j, w-1) cin >> tate[i/2][j];
            }else{
                REP(j, w) cin >> yoko[i/2][j];
            }
        }
        queue<P> que;
        int d[40][40];
        REP(i, h) REP(j, w) d[i][j] = -1;
        que.push(P(0, 0));
        d[0][0] = 1;
        bool exist = false;
        int dx[4] = {1, 0, -1, 0};
        int dy[4] = {0, 1, 0, -1};
        while(!que.empty()){
            P p = que.front(); que.pop();
            if(p.first == h-1 && p.second == w-1){
                exist = true;
                break;
            }
            REP(i, 4){
                int x = p.first + dx[i], y = p.second + dy[i];
                if(x>=0 && x<h && y>=0 && y<w && d[x][y] == -1){
                    if((i==0&&yoko[p.first][p.second]==0)||(i==1&&tate[p.first][p.second]==0)||(i==2&&yoko[p.first-1][p.second]==0)||(i==3&&tate[p.first][p.second-1]==0)){
                        que.push(P(x, y));
                        d[x][y] = d[p.first][p.second] + 1;
                    }
                }
            }
        }
        if(exist) cout << d[h-1][w-1] << endl;
        else cout << 0 << endl;

    }
    return 0;
}