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: def main():
    import queue
    import sys
    input=sys.stdin.readline
    
    while True:
        w,h=map(int,input().split())
        if w==0 and h==0:
            break
        maze=[list(map(int,input().split())) for _ in range(2*h-1)]
    

        q=queue.Queue()
        dist=[[-1]*w for _ in range(h)]
        dist[0][0]=1
        q.put((0,0))
        while q.qsize()!=0:
            p=q.get()
            ny=p[0]
            nx=p[1]

            y=ny
            x=nx+1
            if  x<w and dist[y][x]==-1 and maze[2*y][nx]==0:
                dist[y][x]=dist[ny][nx]+1
                q.put((y,x))
            
            y=ny
            x=nx-1
            if x>=0 and dist[y][x]==-1 and maze[2*y][x]==0:
                dist[y][x]=dist[ny][nx]+1
                q.put((y,x))
        
            y=ny+1
            x=nx
            if y<h and dist[y][x]==-1 and maze[2*ny+1][x]==0:
                dist[y][x]=dist[ny][nx]+1
                q.put((y,x))
        
            y=ny-1
            x=nx
            if y>=0 and dist[y][x]==-1 and maze[2*ny-1][x]==0:
                dist[y][x]=dist[ny][nx]+1
                q.put((y,x))
        
        if dist[-1][-1]==-1:
            print(0)
        else:
            print(dist[-1][-1])

if __name__=='__main__':
    main()

Python: # -*- coding: utf-8 -*-
from collections import defaultdict, deque
W, H = map(int, input().split())

while W:
    G = defaultdict(list)
    for h in range(H):
        for w, b in enumerate(map(int, input().split())):
            if b == 0:
                G[(w, h)].append((w+1, h))
                G[(w+1, h)].append((w, h))
        if h == H-1:
            break
        for w, b in enumerate(map(int, input().split())):
            if b == 0:
                G[(w, h)].append((w, h+1))
                G[(w, h+1)].append((w, h))

    dist = defaultdict(lambda: 1000)
    Q = deque([(0, 0)])
    dist[(0, 0)] = 1
    found = False
    while Q:
        x, y = Q.pop()
        c = dist[(x, y)]
        for px, py in G[(x, y)]:
            if (px, py) == (W-1, H-1):
                print(c+1)
                Q = []
                found = True
                break
            elif dist[(px, py)] >= c+1:
                dist[(px, py)] = c+1
                Q.append((px, py))
    if not found:
        print(0)
    W, H = map(int, input().split())

Python: from collections import deque
INF = float('INF')

while(1):
  w, h = map(int, input().split())
  if(w == 0 and h == 0):
    break
  wall = list() #偶数行が縦の壁、奇数行が横の壁
  for i in range(h*2-1):
    wall.append(list(map(int, input().split())))
  dist = [[INF] * w for _ in range(h)]
  dist[0][0] = 1
  q = deque([(0, 0)])
  while q:
    x, y = q.popleft()
    if(y >= 1): #左
      if(dist[x][y-1] == INF):
        if(wall[x*2][y-1] == 0):
          dist[x][y-1] = dist[x][y] + 1
          q.append((x, y-1))
    if(y <= w-2): #右
      if(dist[x][y+1] == INF):
        if(wall[x*2][y] == 0):
          dist[x][y+1] = dist[x][y] + 1
          q.append((x, y+1))
    if(x >= 1): #上
      if(dist[x-1][y] == INF):
        if(wall[2*x-1][y] == 0):
          dist[x-1][y] = dist[x][y] + 1
          q.append((x-1, y))
    if(x <= h-2): #下
      if(dist[x+1][y] == INF):
        if(wall[2*x+1][y] == 0):
          dist[x+1][y] = dist[x][y] + 1
          q.append((x+1, y))
    
  if(dist[h-1][w-1] == INF):
    print(0)
  else:
    print(dist[h-1][w-1])

Python: from collections import deque
import sys
import copy


def input():
    return sys.stdin.readline()[:-1]


while True:
    w, h = map(int, input().split())

    if w == h == 0:
        exit(0)

    M = []
    for _ in range(h*2-1):
        tmp = input()
        if len(tmp) != w*2-1:
            tmp = tmp+' '
        M.append(list(tmp))
    check = copy.deepcopy(M)
    check[0][0] = '1'

    que = deque([])
    que.append((0, 0, 1))
    mv_list = [(1, 0, 2, 0), (-1, 0, -2, 0), (0, 1, 0, 2), (0, -1, 0, -2)]
    while True:
        if not(que):
            print(0)
            break

        nm = que.popleft()
        if nm[0] == (w*2-2) and nm[1] == (h*2-2):
            print(nm[2])
            break

        for mv in mv_list:
            x1 = nm[0] + mv[0]
            x2 = nm[0] + mv[2]
            y1 = nm[1] + mv[1]
            y2 = nm[1] + mv[3]
            if 0 <= x1 <= w*2-1 and 0 <= y1 <= h*2-1 and 0 <= x2 <= w*2-1 and 0 <= y2 <= h*2-1 and M[y1][x1] == '0' and check[y2][x2] == ' ':
                check[y2][x2] = ''
                que.append((x2, y2, nm[2]+1))