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 pb(n) push_back(n)
#define fi first
#define se second
#define all(r) (r).begin(),(r).end()
#define gsort(st,en) sort((st),(en),greater<int>())
#define vmax(ary) *max_element(all(ary))
#define vmin(ary) *min_element(all(ary))
#define debug(x) cout<<#x<<": "<<x<<endl
#define fcout(n) cout<<fixed<<setprecision((n))
#define scout(n) cout<<setw(n)
#define vary(type,name,size,init) vector< type> name(size,init)
#define vvl(v,w,h,init) vector<vector<ll>> v(w,vector<ll>(h,init));

#define rep(i,n) for(int i = 0; i < (int)(n);++i)
#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)
#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)
#define repa(n,array) for(auto &n :(array))

using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using dict = map<string,int>;
using pii = pair<int,int> ;
using pll = pair<ll,ll> ;

const int mod = 1000000007;
constexpr int imax = ((1<<30)-1)*2+1 ;
constexpr int inf = 100000000;
constexpr double PI = acos(-1.0) ;
double eps = 1e-10 ;
const int dy[] = {-1,0,1,0,1,-1,1,-1};
const int dx[] = {0,-1,0,1,1,-1,-1,1};

inline bool value(int x,int y,int w,int h){
  return (x >= 0 && x < w && y >= 0 && y < h);
}

template<typename T>
void Unique(vector<T> &v){
  sort(all(v));
  v.erase(unique(all(v)),v.end());
}

template<typename T>
T ston(string& str, T n){
  istringstream sin(str) ;
  T num ;
  sin >> num ;
  return num ;
}

void Ans(bool f){
  if(f) cout << "YES"<<endl;
  else cout << "NO"<<endl;
}

int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  ll w,h;
  while(cin >> w >> h && w && h){
    vector<vector<ll>> v(w * 2+1,vector<ll>(h*2+1,0));
    rep(j,h-1){
      rep(i,w-1){
        cin >> v[i*2+1][2*j];
      }
      rep(i,w){
        cin >> v[i*2][2*j+1];
      }
    }
    rep(i,w-1){
      cin >> v[i*2+1][(h-1)*2];
    }
    queue<pll> q;
    q.push({0,0});
    v[0][0] = 1;
    ll depth = 1;
    while(q.size()){
      ll s = q.size();
      rep(i,s){
        if(q.size()){
          auto p = q.front();q.pop();
          v[p.fi][p.se] = depth;
          rep(i,4){
            int nx = p.fi + dx[i]*2,ny = p.se + dy[i]*2;
            if(value(nx,ny,w*2,h*2) && v[nx][ny] == 0){
              if(value(nx-dx[i],ny-dy[i],w*2+1,h*2-1) && v[nx-dx[i]][ny-dy[i]] == 0){
                q.push({nx,ny});
                if(nx == (w-1)*2 && ny == (h-1)*2){
                  v[nx][ny] = depth+1;
                  q = queue<pll>();
                  i = s;
                  break;
                }
              }
            }
          }
        }
      }
      ++depth;
      if(q.size() > 100000 || depth > 900) break;
    }
//     rep(i,h*2){
//       rep(j,w*2+1){
//         cout << v[j][i]<< " ";
//       }
//       cout << endl;
//     }
    cout << v[(w-1)*2][(h-1)*2]<<endl;
  }
  return 0;
}

C++: #include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
const int INF=1<<29,MOD=1e9+7;

int main(){
	int dx[4]={0,1,0,-1};
    int dy[4]={-1,0,1,0};
	int w,h;
	queue<pair<int,int>> q;

	while(cin>>w>>h && w>0){
		bool wall[4][h][w];
		rep(i,w) wall[0][0][i]=wall[2][h-1][i]=1;
		rep(i,h) wall[3][i][0]=wall[1][i][w-1]=1;
		// bool up[h][w],right[h][w],left[h][w],down[h][w];
		// rep(i,w-1) up[0][i]=down[h-1][w-2-i]=1;
		// rep(i,h) left[i][0]=right[i][w-1]=1;
		int d[h][w];
	    rep(i,h)rep(j,w)d[i][j]=INF;
		int y=0;
		while(y<h){
			int x;
			rep(j,w-1){
				cin>>x; //cout<<x;
				wall[1][y][j]=wall[3][y][j+1]=x;
				// right[y][j]=left[y][j+1]=x;
			}if(y!=h-1)rep(j,w){
				cin>>x; //cout<<x;
				wall[2][y][j]=wall[0][y+1][j]=x;
				// down[y][j]=up[y+1][j]=x;
			}
			y++;
		}
		// rep(i,h)rep(j,w){
		// 	rep(k,4)cout<<wall[k][i][j];
		// 	cout<<endl;
		// }
		d[0][0]=1;
	    q.push(make_pair(0,0));

		while(q.size()){
	        pair<int,int> p=q.front(); //qの最右を取り出す
	        q.pop(); //取り出したら削除
			//cout<<p.first<<" "<<p.second<<endl;
	        int prev=d[p.first][p.second]; //一手前の手数prev
	        rep(i,4){ //4方向探索
	            int cy=p.first+dy[i];
	            int cx=p.second+dx[i];
				if(0<=cy and cy<h and 0<=cx and cx<w){
					if(!wall[i][p.first][p.second] and d[cy][cx]==INF){ //通行可能かつ未到達
		                d[cy][cx]=prev+1;
		                q.push(make_pair(cy,cx)); //突っ込む
		            }
				}
	        }
	    }
		//rep(i,h)rep(j,w)cout<<d[i][j]<<endl;
		if(d[h-1][w-1]==INF) cout<<0<<endl;
	    else cout<<d[h-1][w-1]<<endl;
	}
	return 0;
}