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>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep2(i, s, n) for (int i = s; i < (int)(n); i++)
#define rep3(i, s, n) for (int i = s; i > (int)(n); i--)
#define all(obj) obj.begin(), obj.end()
#define db(x) cerr << #x << ":" << x << " "
#define dbl(x) cerr << #x << ":" << x << "\n"
#define dbv(vec) cerr << #vec << ":"; for (auto e : vec) cerr << e << ", "; cout << "\n"
#define dbvv(vv) cerr << #vv << ":\n"; for (auto vec : vv) { for (auto e : vec) cerr << e << ", "; cerr << "\n"; }
#define dbm(map) cerr << #map << ":"; for (auto p : map) cerr << "(" << p.first << ", " << p.second << "), "; cerr << "\n";
#define YN(f) cout << (f ? "YES" : "NO") << "\n"
#define Yn(f) cout << (f ? "Yes" : "No") << "\n"
#define yn(f) cout << (f ? "yes" : "no") << "\n"
using ll = long long;
using vi = vector<int>; using vl = vector<ll>; using vs = vector<string>; using vb = vector<bool>;
using vvi = vector<vi>; using vvl = vector<vl>; using vvb = vector<vb>;
using pii = pair<int, int>; using pll = pair<ll, ll>;
using vpii = vector<pii>; using vpll = vector<pll>;
using ti3 = tuple<int, int, int>; using tl3 = tuple<ll, ll, ll>;
using mii = map<int, int>; using mil = map<int, ll>; using mli = map<ll, int>; using mll = map<ll, ll>;

int main() {
	while (true) {
		int w, h; cin >> w >> h;
		if (h == 0 and w == 0) break;
		vector<vvb> g(h, vvb(w, vb(4))); // g[i][j][k]:(i, j)から下/右/上/左に進めるか	
		rep(i, h - 1) {
			rep(j, w - 1) {
				int t; cin >> t;				
				if (t == 0) g[i][j][1] = g[i][j + 1][3] = true;
			}
			rep(j, w) {
				int t; cin >> t;
				if (t == 0) g[i][j][0] = g[i + 1][j][2] = true;
			}
		}
		rep(j, w - 1) {
			int t; cin >> t;				
			if (t == 0) g[h - 1][j][1] = g[h - 1][j + 1][3] = true;
		}
		/*
		rep(k, 4) {
			rep(i, h) {
				rep(j, w) cout << g[i][j][k];
				cout << endl;
			}
			cout<< endl;
		}
		*/
		vvi d(h, vi(w, -1));
		queue<pii> q;
		pii p(0, 0); q.push(p); d[0][0] = 0;
		vi di = { 1, 0, -1, 0 }, dj = { 0, 1, 0, -1 };
		while (!q.empty()) {
			pii u = q.front(); q.pop();
			int ui, uj; tie(ui, uj) = u;
			rep(k, 4) {
				if (!g[ui][uj][k]) continue;
				int vi = ui + di[k], vj = uj + dj[k];
				if (vi < 0 or vi >= h or vj < 0 or vj >= w) continue;
				if (d[vi][vj] != -1) continue;
				d[vi][vj] = d[ui][uj] + 1;
				pii v(vi, vj); q.push(v);				
			}			
		}
		// dbvv(d);
		cout << d[h - 1][w - 1] + 1 << endl;
	}
}

C++: #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int INF = 1000000000;
#define REP(i,s,n) for(int i=(int)(s);i<(int)(n);i++)
#define rep(i,n) REP(i, 0, n)
int W, H;
bool wall[31][31][31][31];//yx-yx
int dist[31][31];
typedef pair<int, int> pint;
const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
int bfs(){
    rep(i, 31) rep(j, 31) dist[i][j] = INF;
    dist[0][0] = 1;
    queue<pint> que;
    que.push(pint(0, 0));
    while(!que.empty()){
        pint now = que.front(); que.pop();
        int cx = now.first, cy = now.second;
        if(cy == H - 1 && cx == W - 1) return dist[cy][cx];
        rep(i, 4){
            int nx = cx + dx[i], ny = cy + dy[i];
            if(nx < 0 || ny < 0 || W <= nx || H <= ny) continue;
            if(wall[cy][cx][ny][nx] || dist[ny][nx] != INF) continue;
            dist[ny][nx] = dist[cy][cx] + 1;
            que.push(pint(nx, ny));
        }
    }
    return 0;
}
int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    while(cin >> W >> H && W){
        memset(wall, 0, sizeof(wall));
        int t;
        rep(i, W - 1){
            cin >> t;
            if(t) wall[0][i + 1][0][i] = wall[0][i][0][i + 1] = true;
        }
        REP(i, 1, H){
            rep(j, W){
                cin >> t;
                if(t) wall[i][j][i - 1][j] = wall[i - 1][j][i][j] = true;
            }
            rep(j, W - 1){
                cin >> t;
                if(t) wall[i][j + 1][i][j] = wall[i][j][i][j + 1] = true;
            }
        }
        cout << bfs() << endl;
    }
    return 0;
}