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(depth > 450) 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>
using namespace std;
#define rep(i,n) for(int i=0;i<(n);i++)
#define MP make_pair
#define PB push_back
typedef long long ll;
bool fx[30][30],fy[30][30];
int d[30][30];
int dx[4]={0,-1,-0,1},dy[4]={1,0,-1,0};
int H,W;
int main(){
	while(cin>>W>>H&&W&&H){
		bool ok=false;
		rep(i,30)rep(j,30){
			d[i][j]=10000;
			fx[i][j]=false;
			fy[i][j]=false;
		}
		rep(i,H){
			rep(j,W-1)cin>>fx[j][i];
			if(i==H-1)break;
			rep(j,W)cin>>fy[j][i];
		}
		queue<pair<int,int> >q;
		q.push(MP(0,0));
		d[0][0]=1;
		while(!q.empty()){
			int x=q.front().first,y=q.front().second;q.pop();
			if(x==W-1&&y==H-1)ok=true;
			if(!fx[x][y]&&x+1<W&&d[x+1][y]>d[x][y]+1){
				q.push(MP(x+1,y));d[x+1][y]=d[x][y]+1;
			}
			if(!fy[x][y]&&y+1<H&&d[x][y+1]>d[x][y]+1){
				q.push(MP(x,y+1));d[x][y+1]=d[x][y]+1;
			}
			if(!fx[x-1][y]&&x-1>=0&&d[x-1][y]>d[x][y]+1){
				q.push(MP(x-1,y));d[x-1][y]=d[x][y]+1;
			}
			if(!fx[x][y-1]&&y-1>=0&&d[x][y-1]>d[x][y]+1){
				q.push(MP(x,y-1));d[x][y-1]=d[x][y]+1;
			}
		}
		if(ok)cout<<d[W-1][H-1]<<endl;
		else cout<<0<<endl;
	}
}