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 <cstdio>
#include <queue>
#define rep(i,n) REP(i,0,n)
#define REP(i,a,n) for(int i = a ; i < (int)n ; i++)

using namespace std;

int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int mp[200][200]={0};
int w,h;

void init_map(int w,int h){
    rep(i,200){
        rep(j,200){
            mp[i][j]=1;
        }
    }
    REP(i,1,2*h){
        REP(j,1,2*w){
            mp[i][j]=0;
        }
    }
}

int main(){
    while(1){
        scanf("%d %d",&w,&h);
        if(!w && !h){break;}
        init_map(w,h);
        int in;
        rep(i,2*h-1){
            if(!(i%2)){
                rep(j,w-1){
                    scanf("%d",&in);
                    rep(k,3){
                        mp[i+k][2*j+2]|=in;
                    }
                }
            }
            else{
                rep(j,w){
                    scanf("%d",&in);
                    rep(k,3){
                        mp[i+1][j*2+k]|=in;
                    }
                }
            }
        }
        queue< pair<int,pair<int,int> > > q;
        q.push(make_pair(1,make_pair(0,1)));
        mp[0][1]=2;
        int turn=0;
        bool reach=false;
        while(!q.empty()){
            pair<int,pair<int,int> > buf=q.front();
            q.pop();
            int x=buf.second.second;
            int y=buf.second.first;
            turn=buf.first;
            if(x==2*w-1 && y==2*h-1){reach=true;break;}
            rep(i,4){
                int xx=x+dx[i];
                int yy=y+dy[i];
                if(!(xx>=1 && xx<2*w && yy>=1 && yy<2*h)){continue;}
                if(!mp[yy][xx]){
                    mp[yy][xx]=2;
                    q.push(make_pair(turn+1,make_pair(yy,xx)));
                }
            }
        }
        if(reach){printf("%d\n",turn/2);}
        else{printf("%d\n",0);}
    }
    return 0;
}

C++: #include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <tuple>
#include <deque>
#include <numeric>
#include <bitset>
#include <iomanip>
#include <cassert>
#include <chrono>
#include <random>
#include <limits>
#include <iterator>
#include <functional>
#include <sstream>
#include <complex>
using namespace std;

using ll = long long;
using ull = uint64_t;
using P = pair<int, int>;
constexpr double EPS = 1e-9;
constexpr int INF = 1001001001;
constexpr int mod = 1000000007;
// constexpr int mod = 998244353;

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

constexpr int dx[4] = {1, -1, 0, 0};
constexpr int dy[4] = {0, 0, 1, -1};

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    for(;;){
        int w, h;
        cin >> w >> h;
        if(w == 0 && h == 0)    return 0;

        // 壁を扱いやすくするために大きさ 0 のマスを導入する。
        // 盤面の大きさは、おおよそ 2 倍になる。
        int W = 2 * w - 1, H = 2 * h - 1;
        vector<vector<int>> a(H, vector<int>(W, 0));
        for(int i = 0; i < H; ++i){
            for(int j = 0; j < w - (i % 2 == 0); ++j){
                cin >> a[i][j * 2 + (i % 2 == 0)];
            }
        }

        vector<vector<int>> dist(H, vector<int>(W, INF));
        queue<P> que;
        dist[0][0] = 1;
        que.emplace(0, 0);
        while(!que.empty()){
            int x = que.front().first, y = que.front().second;
            que.pop();
            // 長さ 0 を示す (x % 2) と (y % 2) は排反になるように操作する
            int lb, ub, cost = 0;
            if(x % 2)   lb = 0, ub = 2;
            else if(y % 2)  lb = 2, ub = 4;
            else    lb = 0, ub = 4, cost = 1;
            for(int i = lb; i < ub; ++i){
                int nx = x + dx[i], ny = y + dy[i];
                if(nx < 0 || nx >= H || ny < 0 || ny >= W)  continue;
                if(a[nx][ny])   continue;
                if(chmin(dist[nx][ny], dist[x][y] + cost)){
                    que.emplace(nx, ny);
                }
            }
        }

        if(dist[H - 1][W - 1] == INF)   dist[H - 1][W - 1] = 0;
        cout << dist[H - 1][W - 1] << '\n';
    }
}