h, w = gets.chomp.split(" ").map(&:to_i) spot = [] arr = [] spot_count = 0 h.times do |i| a = gets.chomp.split(" ").map(&:to_i) arr << a a.each_with_index do |item,j| next if item == 0 spot << [i,j] spot_count += 1 end end island = Array.new(h).map{Array.new(w,false)} count = 0 direction = [[0,-1],[0,1],[1,0],[-1,0]] count = 0 #p spot until spot == [] i,j = spot.pop # puts "---------" # print "i" + "#{i}" + " " + "J" + "#{j}" + "\n" #p island arr[i][j] = 0 direction.each do |x,y| yy = i + y xx = j + x next if (xx < 0 || xx > w-1) || (yy < 0 || yy > h-1) #print "xx"+"#{yy}" + " " + "yy"+"#{xx}" + "\n" next if arr[yy][xx] == 0 arr[yy][xx] = 0 #next if island[yy][xx] == true #island[yy][xx] = true spot << [yy,xx] count += 1 end #p spot end # p spot_count # p count puts spot_count - count