class Q1166
  def printArray ary
    n = ary.length
    a = ary[0].length
    for i in 0..n - 1
      for j in 0..a - 1
        print(ary[i][j].to_s + " ")
      end
      puts ""
    end
  end
  def makeField w,h
    nh = 2*h - 1
    nw = 2*w - 1
    field = Array.new(nh).map{Array.new(nw,1000)}
    for i in 0..nh - 1
      t = gets
      for j in 0..nw - 1
        if (t[j] == ?0) then field[i][j] = -1
        elsif(t[j] == ?1) then field[i][j] = -2
        end
      end
    end
    field

  end
  def doIt
    arg = gets.split(" ").map{|x| x.to_i}
      pos = Struct.new("Position", :h, :w)
    while(arg[0] + arg[1] != 0)
      field = makeField arg[0],arg[1]
      #print field
      queue = Array.new
      queue.push(pos.new(0, 0))
      field[0][0] = 1
      nh = 2*arg[1] - 1
      nw = 2*arg[0] - 1
      while 0 < queue.length
        #print queue
        p = queue.shift
        h = p.h
        w = p.w
        v = field[h][w] + 1
        th = h - 2
        #puts("h = " + h.to_s + ", w = " + w.to_s + ", nh = " + nh.to_s + ", nw = " + nw.to_s)
        if(0 <= th && field[th + 1][w] == -1 && field[th][w] > v)
          field[th][w] = v
          queue.push(pos.new(th, w))
        end
        th = h + 2
        #puts field[th - 1][w]
        #puts v
        if(th < nh && field[th - 1][w] == -1 && field[th][w] > v)
          field[th][w] = v
          queue.push(pos.new(th, w))
        end
        tw = w - 2
        if(0 <= tw && field[h][tw + 1] == -1 && field[h][tw] > v)
          field[h][tw] = v
          queue.push(pos.new(h, tw))
        end
        tw = w + 2
        if(tw < nw && field[h][tw - 1] == -1 && field[h][tw] > v)
          field[h][tw] = v
          queue.push(pos.new(h, tw))
        end
      end
      #printArray field
      puts(field[nh - 1][nw - 1] == 1000? 0 : field[nh - 1][nw - 1])
      arg = gets.split(" ").map{|x| x.to_i}
    end
  end
end

Q1166.new.doIt