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)
}

Python: while True:
    w, h = map(int, input().split())
    if w == 0: break
    goal = (w,h)
    vart = []
    hori = []
    for i in range(2*h-1):
        if i % 2 == 0:
            vart.append(list(map(int, input().split())))
        else:
            hori.append(list(map(int, input().split())))
    node = [[0 for i in range(h)] for i in range(w)]
    queue = [(0,0)]
    while queue:
        p = queue.pop(0)
        x, y = p[0], p[1]
        node[x][y] += 1
        if y-1 >= 0 and hori[y-1][x] == 0 and node[x][y-1] == 0:
            node[x][y-1] = node[x][y]
            queue.append((x,y-1))
        if y+1 < h and hori[y][x] == 0 and node[x][y+1] == 0:
            node[x][y+1] = node[x][y]
            queue.append((x,y+1))
        if x-1 >= 0 and vart[y][x-1] == 0 and node[x-1][y] == 0:
            node[x-1][y] = node[x][y]
            queue.append((x-1,y))
        if x+1 < w and vart[y][x] == 0 and node[x+1][y] == 0:
            node[x+1][y] = node[x][y]
            queue.append((x+1,y))
    print(node[goal[0]-1][goal[1]-1])

Python: while True:
    m,n = map(int,input().split())
    sw = []
    bw = []
    if m == 0 and n == 0:
        break
    for i in range(2*n-1):
        if i % 2 == 0:
            sw.append(list(map(int,input().split())))
        else:
            bw.append(list(map(int,input().split())))
    flag = [[0 for i in range(m)] for j in range(n)]
    l = [(0,0,1)]
    res = 0
    while l:
        bf = l.pop(0)
        if bf[0] == n-1 and bf[1] == m-1:
            res = bf[2]
            break
        flag[bf[0]][bf[1]] = 1
        if 1 <= bf[0] and bw[bf[0]-1][bf[1]] == 0 and flag[bf[0]-1][bf[1]] == 0:
            l.append((bf[0]-1,bf[1],bf[2]+1))
        if bf[1] < m-1 and sw[bf[0]][bf[1]] == 0 and flag[bf[0]][bf[1]+1] == 0:
            l.append((bf[0],bf[1]+1,bf[2]+1))
        if 1 <= bf[1] and sw[bf[0]][bf[1]-1] == 0 and flag[bf[0]][bf[1]-1] == 0:
            l.append((bf[0],bf[1]-1,bf[2]+1))
        if bf[0] < n-1 and bw[bf[0]][bf[1]] == 0 and flag[bf[0]+1][bf[1]] == 0:
            l.append((bf[0]+1,bf[1],bf[2]+1))
    print(res)

C++: #include <bits/stdc++.h> 

#define int long long
#define double long double

#define REP(i, b) for(int i = 0; i < (b); i++)
#define REPS(i, b) for(int i = 1; i <= (b); i++)
#define ALL(v) (v).begin(), (v).end()

#define fi first
#define se second
#define pb push_back
#define mp make_pair

using namespace std;

using pi = pair<int, int>;
using vi = vector<int>;
using vd = vector<double>;
using vs = vector<string>;
using vb = vector<bool>;
using vpi = vector<pi>;
using vvi = vector<vi>;
using vvb = vector<vb>;

const int INF = 1e16;
const int MOD = 1e9+7;

template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }


signed main()
{
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(10);

    while(true)
    {
        int w, h; cin >> w >> h;
        if(w == 0 && h == 0) break;
        vvb wall(2*h-1);
        REP(i, 2*h-1)
        {
            int t;
            REP(j, w-1) cin >> t, wall[i].pb(t);
            if(i % 2 == 1) cin >> t, wall[i].pb(t);
        }
        vvi grid(h, vi(w, INF));
        queue<pi> q;
        // bfs
        grid[0][0] = 1;
        q.push(mp(0, 0));
        while(!q.empty())
        {
            pi p = q.front(); q.pop();
            if(p.fi != 0) // 上
            {
                if(!wall[2*p.fi-1][p.se] && chmin(grid[p.fi-1][p.se], grid[p.fi][p.se]+1)) q.push(mp(p.fi-1, p.se));
            }
            if(p.se != w-1) // 右
            {
                if(!wall[2*p.fi][p.se] && chmin(grid[p.fi][p.se+1], grid[p.fi][p.se]+1)) q.push(mp(p.fi, p.se+1));
            }
            if(p.fi != h-1) // 下
            {
                if(!wall[2*p.fi+1][p.se] && chmin(grid[p.fi+1][p.se], grid[p.fi][p.se]+1)) q.push(mp(p.fi+1, p.se));
            }
            if(p.se != 0) // 左
            {
                if(!wall[2*p.fi][p.se-1] && chmin(grid[p.fi][p.se-1], grid[p.fi][p.se]+1)) q.push(mp(p.fi, p.se-1));
            }
        }
        cout << ((grid[h-1][w-1] == INF) ? 0 : grid[h-1][w-1]) << endl;
    }
}