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(ll i=0;i<n;i++)
#define fi first
#define se second
using ll=long long;
using vl=vector<ll>;
using vvl=vector<vector<ll>>;
using pl=pair<ll,ll>;
const ll INF=4e18;
const ll dy[4]={1,0,-1,0};
const ll dx[4]={0,1,0,-1};
ll H,W;
queue<pl> que;
ll GridBFS(pl start,pl goal,vector<vector<char>> &info,vvl &now,vvl &bit){
    que.emplace(start);
    now[start.fi][start.se]=0;
    while(que.size()){
        ll y=que.front().fi,x=que.front().se;
        que.pop();
        rep(k,4){
            if(bit[y][x]&(1<<k)){
                ll ny=y+dy[k],nx=x+dx[k];
                if(now[ny][nx]>now[y][x]+1){
                    now[ny][nx]=now[y][x]+1;
                    que.emplace(ny,nx);
                }
            }
        }
    }
    return now[goal.fi][goal.se];
}
void solve(ll H,ll W){
    vector<vector<char>> info(H,vector<char>(W));
    vvl bit(H,vl(W,15));
    rep(i,2*H-1){
        if(i%2){
            rep(j,W){
                ll a;cin>>a;
                if(!a)continue;
                bit[i/2][j]-=1;
                bit[i/2+1][j]-=4;
            }
        }
        else{
            rep(j,W-1){
                ll a;cin>>a;
                if(!a)continue;
                bit[i/2][j]-=2;
                bit[i/2][j+1]-=8;
            }
        }
    }
    rep(i,H)bit[i][0]-=8,bit[i][W-1]-=2;
    rep(i,W)bit[0][i]-=4,bit[H-1][i]-=1;
    vvl now(H,vl(W,INF));
    pl start={0,0},goal={H-1,W-1};
    ll k=GridBFS(start,goal,info,now,bit);
    if(k==INF)cout<<0<<endl;
    else cout<<k+1<<endl;
}
int main(){
    while(true){
        cin>>W>>H;
        if(H+W==0)break;
        else solve(H,W);
    }
    return 0;
}

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

int a[40][40];
int b[40][40];
int m[40][40];
int w,h;
int f(int x,int y,int d){
	if(m[x][y]<=d)return 0;
	m[x][y]=d;
	x>0&&!a[x-1][y]&&f(x-1,y,d+1);
	x<w-1&&!a[x][y]&&f(x+1,y,d+1);
	y>0&&!b[x][y-1]&&f(x,y-1,d+1);
	y<h-1&&!b[x][y]&&f(x,y+1,d+1);
	return 0;
}

int main(){
	for(;cin>>w>>h,w;){
		for(int i=0;i<40;i++)for(int j=0;j<40;j++){
			m[i][j]=INT_MAX/3;
		}
		for(int i=0;i<h-1;i++){
			for(int j=0;j<w-1;j++){
				cin>>a[j][i];
			}
			for(int j=0;j<w;j++){
				cin>>b[j][i];
			}
		}
		for(int i=0;i<w-1;i++){
			cin>>a[i][h-1];
		}
		f(0,0,1);
		if(m[w-1][h-1]!=INT_MAX/3){
			cout<<m[w-1][h-1]<<endl;
		}else{
			cout<<0<<endl;
		}
	}
	return 0;
}