H, W = gets.split.map(&:to_i) A = H.times.map { gets.split.map(&:to_i) } DY = [-1, 0, 1, 0] DX = [0, 1, 0, -1] def f(y, x) return if A[y][x] == 0 A[y][x] = 0 4.times do |i| ny = y + DY[i] nx = x + DX[i] next if ny < 0 || nx < 0 || H <= ny || W <= nx next if A[ny][nx] == 0 f(ny, nx) end end ans = 0 H.times do |y| W.times do |x| next if A[y][x] == 0 ans += 1 f(y, x) end end puts ans