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++: #pragma GCC optimize("O3")
#include<bits/stdc++.h> 
using namespace std;
using ll=long long;
using ull=unsigned long long int;
using P=pair<int,int>;
template<class T> using V=vector<T>; 
#define fi first
#define se second
#define all(v) (v).begin(),(v).end()
const ll inf=(1e18);
const ll mod=1000000007;
ll gcd(ll a,ll b) {return b ? gcd(b,a%b):a;}
ll lcm(ll c,ll d){return c/gcd(c,d)*d;}
struct __INIT{__INIT(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(15);}} __init;
template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }
V<int> dy={0,-1,0,1},dx={-1,0,1,0};
int main(){
  while(1){
    int w,h;
    cin>>w>>h;
    if(h==0)return 0;
    V<V<bool>> hh(h,V<bool>(w-1,true)),ww(h-1,V<bool>(w,true));
    for(int i=0;i<2*h-1;i++){
      if(i%2==0){
        for(int j=0;j<w-1;j++){
          int c;cin>>c;
          if(c)hh[i/2][j]=false;
        }
      }else{
          for(int j=0;j<w;j++){
          int c;cin>>c;
          if(c)ww[i/2][j]=false;
        }
      }
    }
    V<V<int>> a(h,V<int>(w,1e4));
    a[0][0]=1;
    queue<P> q;
    q.emplace(0,0);
    while(q.size()){
      int y=q.front().fi,x=q.front().se;
      q.pop();
      for(int i=0;i<4;i++){
        int ny=dy[i]+y,nx=dx[i]+x;
        if(ny<0||ny>=h||nx<0||nx>=w)continue;
        if(dy[i]==-1&&!ww[ny][nx])continue;
        if(dy[i]==1&&!ww[ny-1][nx])continue;
        if(dx[i]==-1&&!hh[ny][nx])continue;
        if(dx[i]==1&&!hh[ny][nx-1])continue;
        if(a[ny][nx]>a[y][x]+1){
          a[ny][nx]=a[y][x]+1;
          q.emplace(ny,nx);
        }
      }
    }
    if(a[h-1][w-1]==1e4)cout<<0<<"\n";
    else cout<<a[h-1][w-1]<<"\n";
  }
}

C++: #include <bits/stdc++.h>
using namespace std;

static const int MAX = 50;
static const int LEFT = 3;
static const int RIGHT = 2;
static const int UP = 1;
static const int DOWN = 0;
static const int INF = 1<<30;

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

int main(){
    int H,W;

    while(1){
        cin>>W>>H;
        if(H == 0 && W == 0) break;
        vector<vector<vector<bool> > > dir(MAX,vector<vector<bool> >(MAX,vector<bool>(4)));

        for(int i=0; i<H; i++){
            for(int j=0; j<W;  j++){
                for(int k=0; k<4; k++){
                    dir[i][j][k] = true;
                }
            }
        }

        for(int i=0; i<W; i++){
            dir[0][i][UP] = false;
        }

        for(int i=0; i<W; i++){
            dir[H-1][i][DOWN] = false;
        }

        for(int i=0; i<H; i++){
            dir[i][0][LEFT] = false;
        }

        for(int i=0; i<H; i++){
            dir[i][W-1][RIGHT] = false;
        }

        for(int i=0; i<2*H-1; i++){
            int len;
            if(i % 2 == 0){
                len = W-1;
            }
            else len = W;

            for(int j=0; j<len; j++){
                int flag;
                cin>>flag;
                if(flag == 1){
                    if(i % 2 != 0){
                        dir[i/2+1][j][UP] = false;
                        dir[i/2][j][DOWN] = false;
                    }

                    else {
                        dir[i/2][j][RIGHT] = false;
                        dir[i/2][j+1][LEFT] = false;
                    }
                }
            }
        }

        vector<vector<int> > dis(MAX,vector<int>(MAX,INF));
        for(int i=0; i<H; i++){
            for(int j=0; j<W; j++){
                dis[i][j] = INF;
            }
        }
        dis[0][0] = 1;

        queue<pair<int,int> > dic;
        dic.push({0,0});

        while(! dic.empty()){
            pair<int,int> v = dic.front();
            dic.pop();
            int x = v.first;
            int y = v.second;

            for(int i=0; i<4; i++){
                if(!dir[x][y][i]) continue;
                int nx,ny;
                nx = x+dx[i];
                ny = y+dy[i];
                if(dis[nx][ny] <= dis[x][y]+1) continue;
                dis[nx][ny] = dis[x][y]+1;
                dic.push({nx,ny}); 
            }
        }

        if(dis[H-1][W-1] == INF) cout<<0<<endl;
        else cout<<dis[H-1][W-1]<<endl;
    }

    return 0;
}