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 FOR(i,k,n) for(int i = (int)(k); i < (int)(n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(a) a.begin(), a.end()
#define MS(m,v) memset(m,v,sizeof(m))
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int, int> pii;
const int MOD = 1e9 + 7;
template<class T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template<class T> T &chmax(T &a, const T &b) { return a = max(a, b); }
template<class T>
istream& operator >> (istream& is, vector<T>& v)
{
	for (auto &i : v) is >> i;
	return is;
}
template<class T>
ostream& operator<<(ostream& os, vector<T>& v)
{
	const string delimiter = "\n";
	REP(i, v.size())
	{
		os << v[i];
		if (i != v.size() - 1) os << delimiter;
	}
	return os;
}
/*--------------------template--------------------*/

int INF = 1e7;

const int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
//const int dx[] = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy[] = { 0, -1, 1, -1, 1, 0, -1, 1 };
bool valid(int x, int y, int h, int w) { return (x >= 0 && y >= 0 && x < h&&y < w); }
int place(int x, int y, int w) { return w*x + y; }

typedef int Weight;
struct Edge
{
	int from, to; Weight cost;
	bool operator < (const Edge& e) const { return cost < e.cost; }
	bool operator > (const Edge& e) const { return cost > e.cost; }
};
typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<Weight> Array;
typedef vector<Array> Matrix;
void add_edge(Graph &g, int from, int to, Weight cost)
{
	g[from].push_back(Edge{ from, to, cost });
}

void dijkstra(Graph &g, int s, Array &d)
{
	d.assign(g.size(), INF);
	d[s] = 0;
	typedef pair<Weight, int> P;
	priority_queue<P, vector<P>, greater<P>> que;
	que.push(P(0, s));
	while (!que.empty())
	{
		Weight dist = que.top().first;
		int v = que.top().second;
		que.pop();
		if (d[v] < dist) continue;
		REP(i, g[v].size())
		{
			Edge e = g[v][i];
			if (d[e.to] > d[v] + e.cost)
			{
				d[e.to] = d[v] + e.cost;
				que.push(P(d[e.to], e.to));
			}
		}
	}
}


int main()
{
	cin.sync_with_stdio(false); cout << fixed << setprecision(10);
	int h, w;
	while (cin >> w >> h, h)
	{
		Graph g(w * h);
		REP(i, h * 2 - 1)
		{
			if (i % 2 == 0)
			{
				int x = i / 2;
				REP(j, w - 1)
				{
					int a; cin >> a;
					if (a == 0)
					{
						add_edge(g, place(x, j, w), place(x, j + 1, w), 1);
						add_edge(g, place(x, j + 1, w), place(x, j, w), 1);
					}
				}
			}
			else
			{
				int x = i / 2;
				REP(j, w)
				{
					int a; cin >> a;
					if (a == 0)
					{
						add_edge(g, place(x, j, w), place(x + 1, j, w), 1);
						add_edge(g, place(x + 1, j, w), place(x, j, w), 1);
					}
				}
			}
		}
		Array d;
		dijkstra(g, 0, d);
		cout << (d[w * h - 1] >= INF ? 0 : d[w * h - 1] + 1) << endl;
	}
	return 0;
}

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

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

int main(void){
  while(true){
    int w, h;
    cin >> w >> h;
    if(w == 0 && h == 0){ break; }

    vector<vector<bool> > canGo(2 * h + 1, vector<bool>(2 * w + 1, false));
    for(int i = 1; i <= 2 * h - 1; i++)
      for(int j = 1; j <= 2 * w - 1; j++)
        canGo[i][j] = true;

    int input;
    for(int i = 1; i <= 2 * h - 1; i++){
      if(i % 2 == 1){
        for(int j = 1; j <= w - 1; j++){
          cin >> input;
          if(input == 1)
            canGo[i][j * 2] = canGo[i + 1][j * 2] = false;
        } 
      }
      else{
        for(int j = 1; j <= w; j++){
          cin >> input;
          if(input == 1)
            canGo[i][j * 2 - 1] = canGo[i][j * 2 - 2] = false;
        }
      }
    }

    int ans = -2;
    queue<pair<int, pair<int, int> > > wait;
    wait.push(make_pair(0, make_pair(1, 1)));
    canGo[1][1] = false;
    while(!wait.empty()){
      int cost = wait.front().first;
      int x = wait.front().second.first;
      int y = wait.front().second.second;
      wait.pop();
      if(x == 2 * h - 1 && y == 2 * w - 1){
        ans = cost;
        break;
      }

      for(int i = 0; i < 4; i++){
        int nextX = x + dx[i];
        int nextY = y + dy[i];
        if(canGo[nextX][nextY]){
          wait.push(make_pair(cost + 1, make_pair(nextX, nextY)));
          canGo[nextX][nextY] = false;
        }
      }
    }

    cout << (ans + 2) / 2 << endl;
  }

  return 0;
}