while (ln = gets.chomp) != "0 0"
  w,h = ln.split.map(&:to_i)
  lnb = Array.new(h).map{Array.new(w-1)}
  rob = Array.new(h-1).map{Array.new(w)}
  for i in 0..(h-1)
    lnb[i] = gets.split.map(&:to_i)
    rob[i] = gets.split.map(&:to_i) if i < h-1
  end
  
  @vis = Array.new(h).map{Array.new(w,0)}
  @vis[0][0] = 1
  @dpt = Array.new(h).map{Array.new(w,0)}
  @dpt[0][0] = 1
  @lns = [0]
  @ros = [0]
  id = 0
  @maxid = 0
  
  def extd(ln, ro, d)
    @lns.push(ln)
    @ros.push(ro)
    @vis[ln][ro] = 1
    @dpt[ln][ro] = d
    @maxid += 1
  end
  
  while id <= @maxid
    ln = @lns[id]
    ro = @ros[id]
    break if ln == h-1 && ro == w-1
    d = @dpt[ln][ro]
    extd(ln, ro-1, d+1) if ro > 0 && lnb[ln][ro-1] == 0 && @vis[ln][ro-1] == 0
    extd(ln, ro+1, d+1) if ro < w-1 && lnb[ln][ro] == 0 && @vis[ln][ro+1] == 0
    extd(ln-1, ro, d+1) if ln > 0 && rob[ln-1][ro] == 0 && @vis[ln-1][ro] == 0
    extd(ln+1, ro, d+1) if ln < h-1 && rob[ln][ro] == 0 && @vis[ln+1][ro] == 0
    id += 1
  end
  puts @dpt[h-1][w-1]
end
