def ok(board, x, y, dx, dy, w, h)
  0 <= x + dx && x + dx < w && 0 <= y + dy && y + dy < h &&
    case [dx, dy]
      when [-1, 0]
        board[y * 2][x - 1] != '1'
      when [0, 1]
        board[y * 2 + 1][x] != '1'
      when [1, 0]
        board[y * 2][x] != '1'
      when [0, -1]
        board[y * 2 - 1][x] != '1'
    end
end

def solve(used, board, w, h)
  q = []
  q << [0, 0, 0, used]
  ans = 0
  until q.empty?
    x, y, n, u = q.shift
    if x == w - 1 && y == h - 1
      ans = n + 1
      break
    end
    [[-1, 0], [0, 1], [1, 0], [0, -1]].each do |dx, dy|
      xx = x + dx; yy = y + dy
      if ok(board, x, y, dx, dy, w, h) && !u[yy][xx]
        nu = u.map(&:dup)
        nu[yy][xx] = true
        q << [xx, yy, n + 1, nu]
      end
    end
  end
  p ans
end

loop do
  w, h = gets.split.map(&:to_i)
  break if w == 0 && h == 0
  board = (2 * h - 1).times.map{ gets.chomp.split }
  visited = h.times.map{ [false] * w }
  visited[0][0] = true
  solve(visited, board, w, h)
end