### constant

INF = 1 << 30

### main

loop do
  w, h = gets.split.map(&:to_i)
  break if (w | h) == 0

  wh = w * h
  edges = wh.times.map{wh.times.map{false}}
  nbrs = wh.times.map{[]}

  for y in (0...h)
    vls = gets.split.map(&:to_i)
    for x in (0...(w - 1))
      if vls[x] == 0
        i0 = y * w + x
        i1 = i0 + 1
        edges[i0][i1] = edges[i1][i0] = true
        nbrs[i0] << i1
        nbrs[i1] << i0
      end
    end

    if y < h - 1
      hls = gets.split.map(&:to_i)
      for x in (0...w)
        if hls[x] == 0
          i0 = y * w + x
          i1 = i0 + w
          edges[i0][i1] = edges[i1][i0] = true
          nbrs[i0] << i1
          nbrs[i1] << i0
        end
      end
    end
  end

  st = 0
  gl = wh - 1

  dists = wh.times.map{INF}
  dists[st] = 1
  q = [st]

  while ! q.empty?
    u = q.shift
    break if u == gl
    ud = dists[u]

    for v in nbrs[u]
      vd = dists[v]
      nvd = ud + 1
      if vd > nvd
        dists[v] = nvd
        q << v if vd >= INF
      end
    end
  end

  dg = dists[gl]
  puts dg >= INF ? 0 : dg
end