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;
typedef long long ll;
// #define int long long

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

#define REP(i, n) for (int i = 0; i < (n); ++i)
#define RREP(i, n) for (int i = (n); i >= 0; --i)
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define RFOR(i, a, b) for (int i = (a); i >= (b); --i)
#define ALL(v) (v).begin(), (v).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" \
                      << " " << __FILE__ << endl;

typedef vector<int> vi;
typedef vector<string> vs;
typedef vector<vi> vvi;
typedef pair<int, int> pii;

void solve(int w, int h) {
    vvi hor, var; 
    REP(i, 2*h-1) {
        int t;
        if (i%2 == 0) t = w-1;
        else t = w;

        vi v(t);
        REP(j, t) cin >> v[j];
        if (i%2 == 0) var.emplace_back(v);
        else hor.emplace_back(v);
    }

    queue<pii> q;
    q.push(pii(0, 0));
    vvi dist(h, vi(w, -1));
    dist[0][0] = 0;

    int dx[] = {0, 1, 0, -1};
    int dy[] = {-1, 0, 1, 0};
    while (!q.empty()) {
        pii now = q.front();
        q.pop();

        REP(i, 4) {
            int nx = now.first + dx[i];
            if (!INRANGE(nx, 0, w-1)) continue;
            int ny = now.second + dy[i];
            if (!INRANGE(ny, 0, h-1)) continue;

            if (dist[ny][nx] != -1) continue;
            if (i == 0) { //↑
                assert(INRANGE(now.second-1, 0, (int)hor.size()));
                assert(INRANGE(now.first, 0, (int)hor[0].size()));
                if (hor[now.second-1][now.first] == 1) continue;
            } else if (i == 1) {//→
                assert(INRANGE(now.second, 0, (int)var.size()));
                assert(INRANGE(now.first, 0, (int)var[0].size()));
                if (var[now.second][now.first] == 1) continue;
            } else if (i == 2) {//↓
                assert(INRANGE(now.second, 0, (int)hor.size()));
                assert(INRANGE(now.first, 0, (int)hor[0].size()));
                if (hor[now.second][now.first] == 1) continue;
            } else {//←
                assert(INRANGE(now.second, 0, (int)var.size()));
                assert(INRANGE(now.first, 0, (int)var[0].size()));
                if (var[now.second][now.first] == 1) continue;
            }

            q.push(pii(nx, ny));
            dist[ny][nx] = dist[now.second][now.first] + 1;
        }
    }

    if (dist[h-1][w-1] == -1) cout << 0 << endl;
    else cout << dist[h-1][w-1]+1 << endl;
}

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

    int w, h;
    while (true)
    {
        cin >> w >> h;
        if (w==0 and h==0) break;

        solve(w, h);
    }
    

    return 0;
}

C++: #define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define ALL(v) v.begin(), v.end()
typedef long long ll;

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

int G[35][35];
int A[35][35];
int B[35][35];

void bfs(pair<int,int> u){
  queue<pair<int,int>> q;
  G[u.first][u.second]=1;
  q.push(u);
  int ny,nx;
  while(!q.empty()){
    auto t=q.front(); q.pop();
    ny=t.first, nx=t.second;
    if(A[ny][nx]==0 && G[ny][nx-1]==0){
      G[ny][nx-1]=G[ny][nx]+1;
      q.push({ny,nx-1});
    }
    if(B[ny][nx]==0 && G[ny-1][nx]==0){
      G[ny-1][nx]=G[ny][nx]+1;
      q.push({ny-1,nx});
    }
    if(A[ny][nx+1]==0 && G[ny][nx+1]==0){
      G[ny][nx+1]=G[ny][nx]+1;
      q.push({ny,nx+1});
    }
    if(B[ny+1][nx]==0 && G[ny+1][nx]==0){
      G[ny+1][nx]=G[ny][nx]+1;
      q.push({ny+1,nx});
    }
  }
}

int main(){
  int w,h;
  while(cin>>w>>h){
    if(w==0 && h==0) return 0;
    
    rep(i,35){
      rep(j,35){
        G[i][j]=0;
        A[i][j]=0;
        B[i][j]=0;
      }
    }
  
    G[1][1]=1;
  
    for(int i=1;i<2*h;i++){
      if(i%2==1){
        for(int j=2;j<w+1;j++) cin>>A[(i+1)/2][j];
      }
      else{
        for(int j=1;j<=w;j++) cin>>B[i/2+1][j];
      }
    }
  
    for(int i=1;i<=w;i++){
      B[1][i]=1;
      B[h+1][i]=1;
    }
    for(int i=1;i<=h;i++){
      A[i][1]=1;
      A[i][w+1]=1;
    }
  
    bfs({1,1});  
    cout<<G[h][w]<<endl;
  }
}