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: # AOJ 1166 - 迷図と命ず

import sys
from collections import deque

while True:
    W, H = map(int, sys.stdin.readline().strip().split())

    if (W == 0) and (H == 0):
        break

    Ph = []  # Partition horizontal  H * (W -1)  横移動を遮る仕切り
    Pv = []  # Partition vertical  (H - 1) * W  縦移動を遮る仕切り

    for h in range(2 * H - 1):
        p = list(map(int, sys.stdin.readline().strip().split()))
        if h % 2 == 0:
            Ph.append(p)
        else:
            Pv.append(p)

    # ----------------------------------------------------
    fp = [[True] * W for _ in range(H)]  # FootPrint  探索済みか判断する

    q = deque()
    counter = 1
    q.append((0, 0, counter))
    fp[0][0] = False

    ans_counter = 0
    while q:
        flag = False
        ux, uy, counter = q.popleft()
        # print(f'ux: {ux}, uy: {uy}, counter: {counter}')

        if (ux == W - 1) and (uy == H -1):
            ans_counter = counter
            break

        for i in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
            vx = ux + i[0]
            vy = uy + i[1]
            # print(f'vx: {vx} vy: {vy}')

            if (vx < 0) or (vx >= W):
                continue
            if (vy < 0) or (vy >= H):
                continue
            if fp[vy][vx] is False:
                continue
            # print(f'vx: {vx}, vy: {vy}')

            if (i[1] == 1) and (Pv[uy][ux] == 0):  # 縦方向の移動　下
                q.append((vx, vy, counter + 1))
                fp[vy][vx] = False
            elif (i[1] == -1) and (Pv[vy][ux] == 0):  # 縦方向の移動　上
                q.append((vx, vy, counter + 1))
                fp[vy][vx] = False
            elif (i[0] == 1) and (Ph[uy][ux] == 0):  # 横方向の移動　右
                q.append((vx, vy, counter + 1))
                fp[vy][vx] = False
            elif (i[0] == -1) and (Ph[uy][vx] == 0):  # 横方向の移動　左
                q.append((vx, vy, counter + 1))
                fp[vy][vx] = False

    print(ans_counter)

Python: from collections import deque
while True:
  w, h = list(map(int, input().split()))
  if w==0:
    break
  visited = [[0 for i in range(w)] for i in range(h)]
  visited[0][0] = 1
  ywall = [[] for i in range(h)]
  xwall = [[] for i in range(h-1)]
  for i in range(h*2-1):
    if i%2==0:
      ywall[i//2] = list(map(int, input().split()))
    else:
      xwall[i//2] = list(map(int, input().split()))
  gx, gy = w-1, h-1
  dx, dy = [1, 0, -1, 0], [0, 1, 0, -1]
  que = deque([(0, 0)])
  while len(que):
    x, y = que.popleft()
    for dxt, dyt in zip(dx, dy):
      nx, ny = x+dxt, y+dyt
      if 0<=nx<w and 0<=ny<h:
        if visited[ny][nx]!=0:
          continue
        if (dxt==1 and ywall[y][x]!=1) or (dxt==-1 and ywall[y][x-1]!=1) or (dyt==1 and xwall[y][x]!=1) or (dyt==-1 and xwall[y-1][x]!=1):
          visited[ny][nx] = visited[y][x]+1
          que.append((nx, ny))
  print(visited[gy][gx])

Python: from collections import deque
dirc = ((-1, 0), (0, 1), (1, 0), (0, -1))
while 1:
    w, h = map(int, input().split())
    if w==0:
        break
    maze = [[[0]*4 for i in range(w)] for _ in range(h)]
    for idx in range(2*h-1):
        if idx%2==0:
            horizon = list(map(int, input().split()))
            for i, j in enumerate(horizon):
                if j==1:
                    maze[idx//2][i][1] = -1
                    maze[idx//2][i+1][3] = -1
        else:
            vertical = list(map(int, input().split()))
            for i, j in enumerate(vertical):
                if j==1:
                    maze[idx//2][i][2] = -1
                    maze[idx//2+1][i][0] = -1
    queue = deque()
    queue.appendleft((0, (0, 0)))
    checked = [[0]*w for _ in range(h)]
    ans = 0
    while queue:
        c, (y, x) = queue.pop()
        c += 1
        if checked[y][x]:
            continue
        checked[y][x] = 1
        if (y, x)==(h-1, w-1):
            ans = c
            break
        for i, (dy, dx) in enumerate(dirc):
            if maze[y][x][i]==-1:
                continue
            ny, nx = y+dy, x+dx
            if nx<0 or nx>=w or ny<0 or ny>=h:
                continue
            if not checked[ny][nx]:
                queue.appendleft((c, (ny, nx)))
    print(ans)