H, W = gets.split.map &:to_i board = $<.map{|s|s.split.join.to_i(2)} used = H.times.map{[false] * W} DIRS = [[0, 1], [0, -1], [1, 0], [-1, 0]] f = ->y, x{ return if !y.between?(0, H-1) return if !x.between?(0, W-1) return if board[y][x] == 0 return if used[y][x] used[y][x] = true DIRS.each{|dy, dx| f[y+dy, x+dx] } } ans = 0 H.times{|i| W.times{|j| next if board[i][j] == 0 next if used[i][j] ans += 1 f[i, j] } } p ans