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)
}

Python: ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))
from collections import deque
y_drct = [-1,0,1,0]
x_drct = [0,1,0,-1]
def wall(y,x,i):
    if i==0:
        if yw[y-1][x] == 0:return 1
        else: return 0
    if i==2:
        if yw[y][x] == 0:return 1
        else: return 0
    if i==1:
        if tw[y][x] == 0:return 1
        else: return 0
    if i==3:
        if tw[y][x-1] == 0:return 1
        else: return 0
while 1:
    w,h = mi()
    if w == 0 and h == 0:
        break
    tw = []
    yw = []
    for i in range(h-1):
        tw.append(li())
        yw.append(li())
    tw.append(li())
    b = [[-1]*w for i in range(h)]
    l = deque()
    l.append((0,0))
    b[0][0] = 1
    while len(l) > 0:
        cy,cx = l.popleft()
        if cy == h-1 and cx == w-1:
            break
        for i in range(4):
            ny,nx = cy+y_drct[i],cx+x_drct[i]
            if 0 <= ny < h and 0 <= nx < w:
                if b[ny][nx] == -1:
                    if wall(cy,cx,i):
                        l.append((ny,nx))
                        b[ny][nx] = b[cy][cx]+1
    if b[h-1][w-1]==-1:
        print(0)
    else:
        print(b[h-1][w-1])

Python: while True:
    w, h = map(int, input().split())
    if w == h == 0:
        break

    #path[x][y][k]... kは0123が上下左右
    path = [[[True] * 4 for _ in range(w)] for _ in range(h)]
    for i in range(2 * h - 1):
        s = list(map(int, input().split()))
        x = i // 2

        if i % 2 == 0:
            for j in range(w-1):
                if s[j] == 1:
                    path[x][j][3] = False
                    path[x][j+1][2] = False
        else:
            for j in range(w):
                if s[j] == 1:
                    path[x][j][1] = False
                    path[x+1][j][0] = False

    from collections import deque
    que = deque()
    move = [(-1, 0, 0), (1, 0, 1), (0, -1, 2), (0, 1, 3)]
    inf = 10 ** 7
    d = [[inf] * w for _ in range(h)]
    que.append((0, 0))
    d[0][0] = 1

    while que:
        px, py = que.popleft()
        if px == h-1 and py == w-1:
            break
        for dx, dy, k in move:
            qx, qy = px + dx, py + dy
            if 0 <= qx < h and 0 <= qy < w \
                and path[px][py][k] == True and d[qx][qy] == inf:
                d[qx][qy] = d[px][py] + 1
                que.append((qx, qy))

    print(0 if d[h-1][w-1] == inf else d[h-1][w-1])

Python: from collections import deque

def get_adj(pos):
    return [(pos[0]-1, pos[1]),
            (pos[0]+1, pos[1]),
            (pos[0], pos[1]-1),
            (pos[0], pos[1]+1),
            ]

def can_go(pos, adj, walls):
    if (pos, adj) not in walls:
        return False
    if walls[(pos, adj)] == 0:
        return True
    return False

def solve(W, H):
    walls = {}
    for r in range(2*H - 1):
        l = list(map(int, input().split()))
        if r % 2 == 0:
            for c in range(len(l)):
                left = (r//2, c)
                right = (r//2, c+1)
                walls[(left, right)] = l[c]
                walls[(right, left)] = l[c]
        else:
            for c in range(len(l)):
                up = (r//2, c)
                down = (r//2 + 1, c)
                walls[(up, down)] = l[c]
                walls[(down, up)] = l[c]
    start = (0, 0)
    goal = (H-1, W-1)
    q = deque()
    q.append((start, 0))
    visited = set()
    while q:
        pos, dist = q.popleft()
        if pos in visited:
            continue
        if pos == goal:
            print(dist + 1)
            return
        visited.add(pos)
        for adj in get_adj(pos):
            if can_go(pos, adj, walls):
                q.append((adj, dist+1))

    print(0)
    return

while True:
    W, H = map(int, input().split())
    if W == 0 and H == 0:
        break
    solve(W, H)