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