# require "pp"

loop do
  w, h = gets.split.map(&:to_i)
  break if w == 0
  lines = [[[false, true]] * (w+1)] # [ ?????´????£?????????????, ???????£????????????? ]
  (2 * h - 1).times do |i|
    y = i / 2 + 1
    if i % 2 == 0
      lines[y] = [[true, false]] # ?£????????????°true
      gets.split.map(&:to_i).each do |ch|
        lines[y] << [false, false] if ch == 0
        lines[y] << [true, false]  if ch == 1
      end
      lines[y] << [true, false] # ??????
    else
      gets.split.map(&:to_i).each.with_index(1) do |ch, ci|
        lines[y][ci][1] = true if ch == 1
      end
    end
  end
  lines[-1].each do |c|
    c[1] = true
  end

  d = []
  queue = [[1, 1]]
  d[1] = []
  d[1][1] = 0
  visited = []
  while queue.size > 0
    cx, cy = queue.shift
    visited[cy] ||= []
    visited[cy][cx] = true # ?¨??????????
    break if cx == w && cy == h

    if !lines[cy-1][cx][1] && !(visited[cy-1] && visited[cy-1][cx]) # ???
      queue << [cx, cy-1]
      d[cy-1] ||= []
      d[cy-1][cx] = d[cy][cx] + 1
    end
    if !lines[cy][cx][1] && !(visited[cy+1] && visited[cy+1][cx]) # ???
      queue << [cx, cy+1]
      d[cy+1] ||= []
      d[cy+1][cx] = d[cy][cx] + 1
    end
    if !lines[cy][cx][0] && !(visited[cy] && visited[cy][cx+1]) # ???
      queue << [cx+1, cy]
      d[cy][cx+1] = d[cy][cx] + 1
    end
    if !lines[cy][cx-1][0] && !(visited[cy] && visited[cy][cx-1]) # ???
      queue << [cx-1, cy]
      d[cy][cx-1] = d[cy][cx] + 1
    end
  end

  puts (d[h] && d[h][w]) ? (d[h][w] + 1) : 0
end