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 <iostream>
#include <queue>
using namespace std;

struct P{
    int x;
    int y;
    int d;
    P() {}
    P(int a, int b, int c) : x(a), y(b), d(c) {}
};

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

int main(){
    int w, h,i,j;
    for(;cin>>w>>h, w||h;){
        int wall[2*h-1][w];
        vector< vector<int> > maze(h, vector<int>(w, 0));
        for(i = 0; i < 2*h-1; i++){
            for(j = 0; j < w - 1 + i%2; j++){
                cin >> wall[i][j];
            }
        }
        queue< P > que;
        que.push( P(0,0,0) );
        P e;
        int ans = 0;
        while( !que.empty() ){
            e = que.front();
            que.pop();
            if( e.x == h-1 && e.y == w-1 ){
                    ans = e.d;
                    break;
            }
            maze[e.x][e.y] = 1;
            for(i=0;i<4;i++){
                int xx = e.x + dx[i], yy = e.y + dy[i];
                if( 0 <= xx && xx < h &&
                    0 <= yy && yy < w &&
                    maze[xx][yy] == 0){
                    if( wall[2*e.x + (1-i%2) - i*(1-i%2)][e.y-i/3] ) continue;
                    que.push( P(xx, yy, e.d+1) );
                }
            }
        }
        cout << ans+!!ans << endl;
    }
    return 0;
}

C++: #include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <bitset>
#include <map>
#include <unordered_map>
#include <list>
#include <numeric>
#include <utility>
#include <iterator>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <ctime>
#include <cassert>

//#define INF 1000000000
#define LINF 9000000000000000000
#define mod 1000000007

#define rep(i,n) for(int i=0;i<int(n);i++)
#define rrep(i,n) for(int i=n-1;i>=0;i--)
#define REP(i,a,b) for(int i=(a);i<int(b);i++)
#define all(x) (x).begin(),x.end()
#define pb push_back
#define mp make_pair

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> pi;

int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int ddx[8]={-1,-1,0,1,1,1,0,-1};
int ddy[8]={0,1,1,1,0,-1,-1,-1};
bool debug=false;

/*---------------------------------------------------*/

#include<iostream>
#include<vector>
#include<queue>

using namespace std;

typedef struct Edge {
	int Cost;
	int To;
	Edge(int t,int c){
		Cost = c;
		To = t;
	}
	bool const operator<(Edge e) const {
		return Cost < e.Cost;
	}
}Edge;


class Dijkstra
{
public:
	Dijkstra(int n,bool dir);
	int I;
	int V;
	int E;
	vector<int> Cost;
	void AddPath(int f, int t, int c);
	bool PathExist(int t);
	void Run(int f);
private:
	bool isNonDir = true;
	int INF = 100000000;
	vector<vector<Edge>> Adj;
};

Dijkstra::Dijkstra(int n,bool dir)
{
	isNonDir = dir;
	I = n + 1;
	V = n;
	Adj.resize(I);

}


void Dijkstra::AddPath(int f, int t, int c)
{
	E++;
	Adj[f].push_back(Edge(t, c));
	if (isNonDir) Adj[t].push_back(Edge(f, c));
}

bool Dijkstra::PathExist(int t)
{
	return Cost[t] != INF;
}

void Dijkstra::Run(int f)
{
	//プライオリティキュー
	priority_queue<Edge> pq;
	//コストをしまう配列
	Cost.resize(I);
	for (int i = 0; i < I; i++)
	{
		Cost[i] = INF;
	}
	//スタート地点からスタート地点への距離は0
	Cost[f] = 0;
	//初期位置をエンキュー
	pq.push(Edge(f, 0L));

	//キューが空になるまで
	while (!pq.empty())
	{
		//先頭を取り出す
		auto cur = pq.top();
		pq.pop();

		//取り出したやつのコストがすでに決まってるやつより大きかったらバイバイ
		if (Cost[cur.To] < cur.Cost) continue;
		//隣接リストを探索
		for (int i = 0; i < (int)Adj[cur.To].size(); i++)
		{
			auto tmp = Adj[cur.To][i];
			//取り出した値を
			if (Cost[tmp.To] > cur.Cost + tmp.Cost) {
				Cost[tmp.To] = cur.Cost + tmp.Cost;
				pq.push(Edge(tmp.To, Cost[tmp.To]));
			}
		}
        }
}


void solve(int w,int h){
  int x;
  Dijkstra dij(w * h,true);
  rep(i,h*2-1){
    if(i%2==0){
      rep(j,w-1){
	cin>>x;
	if(x==0)dij.AddPath(i/2*w+j,i/2*w+j+1,1);
      }
    }else{
      rep(j,w){
	cin>>x;
	if(x==0)dij.AddPath(i/2*w+j,(i/2+1)*w+j,1);
      }
    }
  }

  dij.Run(0);
  /*
  rep(i,h){
    rep(j,w){
      cout<<dij.Cost[i*w+j]<<" ";
    }
    cout<<endl;
  }
  */
  if(dij.Cost[h*w-1]!=100000000)cout<<dij.Cost[h*w-1]+1<<endl;
  else cout<<0<<endl;
}

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