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: from collections import deque
INF = 10 ** 10

def search(nowi, nowj, next, root, yoko, tate):
    global INF
    if nowi == h - 1 and nowj == w - 1:
        return root[nowi][nowj]
    # print(nowi, nowj, len(yoko), len(tate), h, w, yoko, tate)
    dis = root[nowi][nowj]
    if 0 < nowi:
        if root[nowi - 1][nowj] == INF and tate[nowi - 1][nowj] == 0:
            next.append([nowi - 1, nowj])
            root[nowi - 1][nowj] = dis + 1
    if 0 < nowj:
        if root[nowi][nowj - 1] == INF and yoko[nowi][nowj - 1] == 0:
            next.append([nowi, nowj - 1])
            root[nowi][nowj - 1] = dis + 1
    if nowi < len(root) - 1:
        if root[nowi + 1][nowj] == INF and tate[nowi][nowj] == 0:
            next.append([nowi + 1, nowj])
            root[nowi + 1][nowj] = dis + 1 
    if nowj < len(root[nowi]) - 1:
        if root[nowi][nowj + 1] == INF and yoko[nowi][nowj] == 0:
            next.append([nowi, nowj + 1])
            root[nowi][nowj + 1] = dis + 1
    if len(next) == 0:
        return 0
    nextij = next.popleft()
    nexti = nextij[0]
    nextj = nextij[1]
    return search(nexti, nextj, next, root, yoko, tate)


while True:
    w, h = map(int, input().split())
    if w == 0 and h == 0:
        break
    yoko = []
    tate = []

    for i in range(2 * h - 1):
        if i % 2 == 0:
            yoko.append(list(map(int, input().split())))
        else:
            tate.append(list(map(int, input().split())))
    
    root = [[INF for _ in range(w)] for _ in range(h)]
    root[0][0] = 1
    next = deque()
    print(search(0, 0, next, root, yoko, tate))

Python: from collections import deque
while True:
    W, H = map(int, input().split())
    if W==0 and H==0:
        break
    #それぞれのマスの上下左右の壁があるかどうかを記録
    grid = [ [ [0]*4 for _ in range(W)] for _ in range(H)] 
    #print(grid)
    #壁を埋める
    for i in range(H):
        grid[i][0][0] = 1
        grid[i][-1][1] = 1
    
    for i in range(W):
        grid[0][i][2] = 1
        grid[-1][i][3] = 1
    
    #入口と出口は空ける
    # grid[0][0][2] = 0
    # grid[-1][-1][3] = 0  

    #入力受取 
    for i in range(2*H-1):
        a = list(map(int, input().split()))
        #縦の壁
        if i%2==0:
            for j in range(W-1):
                if a[j] == 1:
                    grid[i//2][j][1] = 1
                    grid[i//2][j+1][0] = 1
        #横の壁
        else:
            for j in range(W):
                if a[j] == 1:
                    grid[i//2][j][3] = 1
                    grid[i//2+1][j][2] = 1
        
    #print(grid)

    dist = [[-1]*W for _ in range(H)]
    dist[0][0] = 0
    #print(dist)

    que = deque()
    que.append([0,0])

    #左右上下 y,x
    d = [[0,-1],[0,1],[-1,0],[1,0]]

    while que:
        #print(que)
        y,x = que.popleft()
        for i in range(4):
            if grid[y][x][i] == 0:
                dy = y + d[i][0]
                dx = x + d[i][1]
                if dist[dy][dx] == -1:
                    que.append([dy,dx])
                    dist[dy][dx] = dist[y][x]+1
    
    if dist[-1][-1] == -1:
        print(0)
    else:
        print(dist[-1][-1]+1)

Python: #importを忘れずに
import queue
w,h=map(int,input().split())
while w!=0 or h!=0:
    #壁の情報
    maps=[]
    for i in range(h*2-1):
        k=list(map(int,input().split()))
        maps.append(k)
    
    #壁による移動制限のチェック
    def check(x,y,x2,y2):
        global maps
        if x2<0 or x2>=w or y2<0 or y2>=h:
            return False
        if x==x2:
            if maps[y+y2][x]!=0:
                return False
        if y==y2:
            if maps[y*2][(x+x2)//2]!=0:
                return False
        return True

    def bfs():
        #queueをつくる
        q=queue.Queue()
        #rawmapはその地点までの最短距離をあらわす
        rawmap=[[0]*h for i in range(w)]
        #移動4方向のベクトル
        dx=[1,0,-1,0]
        dy=[0,1,0,-1]
        #putでqueueにいれる
        q.put([0,0])
        rawmap[0][0]=1
        #pythonでは0以外の数値はTrueとして扱われる
        while q.qsize():
            #getでqueueから取り出す
            x,y=q.get()
            if x==w-1 and y==h-1:
                break
            for i in range(4):
                x2=x+dx[i]
                y2=y+dy[i]
                if check(x,y,x2,y2) and rawmap[x2][y2]==0:
                    q.put([x2,y2])
                    rawmap[x2][y2]=rawmap[x][y]+1
        return rawmap[w-1][h-1]
        
    print(bfs())
    w,h=map(int,input().split())