h, w = gets.split.map(&:to_i) memo = {} h.times {|i| s = gets.split.map(&:to_i) w.times {|j| if s[j] == 1 memo[[i, j]] = true end } } ans = 0 memo.keys.each do |i, j| next if memo[[i, j]] != true ans += 1 s = [[i, j]] while s.size > 0 i, j = s.pop next if memo[[i, j]] != true memo[[i, j]] = false s << [i+1, j] s << [i-1, j] s << [i, j+1] s << [i, j-1] end end p ans