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 <cstdio>
#include <utility>
#include <vector>
#include <queue>
using namespace std;

#define gcu getchar_unlocked
int in(int c){int n=0;bool m=false;if(c=='-')m=true,c=gcu();
	do{n=10*n+(c-'0'),c=gcu();}while(c>='0');return m?-n:n;} //&&c<='9'
int in() {return in(gcu());}
bool scan(int &n){int c=gcu();return c==EOF?false:(n=in(c),true);}
bool scan(char &c){c=gcu();gcu();return c!=EOF;}
//bool scan(string &s){int c;s="";
//	for(;;){c=gcu();if(c=='\n'||c==' ')return true;else if(c==EOF)return false;s+=c;}}
template <typename head, typename... tail>
bool scan(head &h, tail&&... t){return scan(h) && scan(t...);}
#define pcu putchar_unlocked
#define vo inline void out
template <typename T>
vo(T n){static char buf[20];char *p=buf;
	if(n<0)pcu('-'),n*=-1;if(!n)*p++='0';else while(n)*p++=n%10+'0',n/=10;
	while (p!=buf)pcu(*--p);}
vo(const char *s){while(*s)pcu(*s++);}
vo(char c){pcu(c);}
//vo(string &s){for (char c: s) pcu(c);}
template <typename head, typename... tail> vo(head&& h, tail&&... t){out(h);out(move(t)...);}
//template <typename T> vo(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);out('\n');}
#undef vo

struct node {int x, y, d;};
typedef vector<bool> vb;

int main() {
	for (int w, h; w = in(), h = in(), w || h;) {
		vector<vb> m(h * 2 + 1, vb(w + 2));
		for (size_t i = 1; i < m.size() - 1; i++)
			for (int j = 1, e = i % 2 ? (gcu(), w - 1) : w; j < e + 1; j++)
				m[i][j] = !in();
		vector<vb> v(h + 1, vb(w + 1));
		int r = 0;
		queue<node> q;
		for (q.push({1, 1, 1}); !q.empty(); q.pop()) {
			node n = q.front();
			if (n.x == w && n.y == h)
				r = n.d;
			if (v[n.y][n.x])
				continue;
			v[n.y][n.x] = true;
			static int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1},
					   tx[] = {0, 0, -1, 0}, ty[] = {-1, 0, -1, -2};
			for (int i = 0; i < 4; i++)
				if (m[n.y * 2 + ty[i]][n.x + tx[i]] && !v[n.y + dy[i]][n.x + dx[i]])
					q.push({n.x + dx[i], n.y + dy[i], n.d + 1});
		}
		out(r, '\n');
	}
}

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

struct state{int y,x,cost;};

int dy[]={-1,0,1,0};
int dx[]={0,1,0,-1};
int t[50][50][2];
int H,W,a;
bool visited[50][50];

bool inField(int y,int x){
  if(y<0||y>=H)return false;
  if(x<0||x>=W)return false;
  return true;
}
int check(int y,int x,int dir){
  if(dir==0)return t[y-1][x][1];
  if(dir==1)return t[y][x][0];
  if(dir==2)return t[y][x][1];
  if(dir==3)return t[y][x-1][0];
}

void init(){
  for(int i=0;i<50;i++)
    for(int j=0;j<50;j++)visited[i][j]=false;
}

void solve(){
  queue< state >Q;
  Q.push((state){0,0,1});
  while(!Q.empty()){
    state s = Q.front();Q.pop();
    if(visited[s.y][s.x])continue;
    visited[s.y][s.x]=true;
    if(s.y==H-1&&s.x==W-1){cout<<s.cost<<endl;return;}
    for(int i=0;i<4;i++){
      int ny=s.y+dy[i],nx=s.x+dx[i];
      if(!inField(ny,nx))continue;
      if(check(s.y,s.x,i)==1)continue;
      Q.push((state){ny,nx,s.cost+1});
    }
  }
  cout<<0<<endl;
}

int main(){
  while(cin>>W>>H&&W&&H){
    for(int i=0;i<H-1;i++){
      for(int j=0;j<W-1;j++)cin>>t[i][j][0];
      for(int j=0;j<W;j++)cin>>t[i][j][1];
    }
    for(int j=0;j<W-1;j++)cin>>t[H-1][j][0];
    init();
    solve();
  }
  return 0;
}