## https://yukicoder.me/problems/no/697 from collections import deque DIRECTIONS = [(-1, 0), (1, 0), (0, 1), (0, -1)] def main(): H, W = map(int, input().split()) A = [] for _ in range(H): A.append(list(map(int, input().split()))) composite_id_cell = [[-1] * W for _ in range(H)] composite_id = 0 queue = deque() for s_h in range(H): for s_w in range(W): if A[s_h][s_w] == 1 and composite_id_cell[s_h][s_w] == -1: composite_id_cell[s_h][s_w] = composite_id queue.append((s_h, s_w)) while len(queue) > 0: h, w = queue.popleft() for dh, dw in DIRECTIONS: new_h = dh + h new_w = dw + w if 0 <= new_h < H and 0 <= new_w < W: if A[new_h][new_w] == 1 and composite_id_cell[new_h][new_w] == -1: composite_id_cell[new_h][new_w] = composite_id queue.append((new_h, new_w)) composite_id += 1 print(composite_id) if __name__ == "__main__": main()