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 <iostream>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <complex>
#include <utility>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
#include <bitset>
#include <ctime>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <cassert>
#include <cstddef>
#include <iomanip>
#include <numeric>
#include <tuple>
#include <sstream>
#include <fstream>

using namespace std;
#define REP(i, n) for (int (i) = 0; (i) < (n); (i)++)
#define FOR(i, a, b) for (int (i) = (a); (i) < (b); (i)++)
#define RREP(i, a) for(int (i) = (a) - 1; (i) >= 0; (i)--)
#define FORR(i, a, b) for(int (i) = (a) - 1; (i) >= (b); (i)--)
#define DEBUG(C) cerr << #C << " = " << C << endl;
using LL = long long;
using VI = vector<int>;
using VVI = vector<VI>;
using VL = vector<LL>;
using VVL = vector<VL>;
using VD = vector<double>;
using VVD = vector<VD>;
using PII = pair<int, int>;
using PDD = pair<double, double>;
using PLL = pair<LL, LL>;
using VPII = vector<PII>;
#define ALL(a) begin((a)), end((a))
#define RALL(a) rbegin((a)), rend((a))
#define SORT(a) sort(ALL((a)))
#define RSORT(a) sort(RALL((a)))
#define REVERSE(a) reverse(ALL((a)))
#define MP make_pair
#define FORE(a, b) for (auto &&a : (b))
#define FIND(s, e) ((s).find(e) != (s).end())
#define EB emplace_back

const int INF = 1e9;
const int MOD = INF + 7;
const LL LLINF = 1e18;

int nh[] = {-1, 0, 0, 1};
int nw[] = {0, -1, 1, 0};
void solve(int w, int h) {
    VVI mini(h, VI(w, INF));
    auto inside = [&h, &w](int nh, int nw) {
        return 0 <= nw && nw < w && 0 <= nh && nh < h;
    };
    vector<vector<VPII>> graph(h, vector<VPII>(w));
    REP(i, h) {
        int in;
        REP(j, w - 1) {
            cin >> in;
            if (in) continue;
            graph[i][j].EB(MP(i, j + 1));
            graph[i][j + 1].EB(MP(i, j));
        }
        if (i != h - 1) REP(j, w) {
            cin >> in;
            if (in) continue;
            graph[i][j].EB(MP(i + 1, j));
            graph[i + 1][j].EB(MP(i, j));
        }
    }
    queue<PII> q;
    q.push(MP(0, 0));
    mini[0][0] = 1;
    while (!q.empty()) {
        int nw, nh;
        tie(nh, nw) = q.front();q.pop();
        FORE(e, graph[nh][nw]) {
            if (!inside(e.first, e.second)) continue;
            if (mini[e.first][e.second] != INF) continue;
            mini[e.first][e.second] = mini[nh][nw] + 1;
            q.push(MP(e.first, e.second));
        }
    }
    if (mini[h - 1][w - 1] == INF) mini[h - 1][w - 1] = 0;
    cout << mini[h - 1][w - 1] << endl;
    return;
}

signed main(void) {
    int n, m, p, a, b, c, x, y, z, q;
    string s;
    bool f = false;
    while (cin >> n >> m, n) {
        solve(n, m);
        //return 0;
    }
}

C++: #include<iostream>
#include<vector>
#include<queue>
using namespace std;

const int INF = 1<<30;

int main(){
    int w, h;
    while(cin >> w >> h, w+h){
        int mat[2*h-1][w];
        for(int i = 0; i < 2*h-1; i++){
            for(int j = 0; j < w-((i+1)%2); j++){
                cin >> mat[i][j];
            }
        }
        vector<vector<int>> dp(h, vector<int>(w, INF));
        dp[0][0] = 1;
        queue<pair<int,int>> pq;
        pq.push({0,0});
        while(!pq.empty()){
            auto p = pq.front();    pq.pop();
            int i = p.first, j = p.second;
            // north
            if(i != 0 && mat[2*i-1][j] == 0 && dp[i][j]+1 < dp[i-1][j]){
                dp[i-1][j] = dp[i][j]+1;    pq.push({i-1, j});
            }
            // south
            if(i != h-1 && mat[2*(i+1)-1][j] == 0 && dp[i][j]+1 < dp[i+1][j]){
                dp[i+1][j] = dp[i][j]+1;    pq.push({i+1, j});
            }
            // west
            if(j != 0 && mat[2*i][j-1] == 0 && dp[i][j]+1 < dp[i][j-1]){
                dp[i][j-1] = dp[i][j]+1;    pq.push({i, j-1});
            }
            // east
            if(j != w-1 && mat[2*i][j] == 0 && dp[i][j]+1 < dp[i][j+1]){
                dp[i][j+1] = dp[i][j]+1;    pq.push({i, j+1});
            }
        }
        cout << (dp[h-1][w-1]==INF ? 0 : dp[h-1][w-1]) << endl;
    }
    return 0;
}