백준 2667번 단지번호붙이기 파이썬

from collections import deque
import sys

N = int(input())

M = [[0] * N for _ in range(N)]

for i in range(N):
    line = sys.stdin.readline()
    for j in range(N):
        M[i][j] = int(line[j])

dr = [-1, 1, 0, 0]
dc = [0, 0, -1, 1]


def bfs(x, y):
    queue = deque()
    queue.append((x, y))
    M[x][y] = 0
    cnt = 1
    global num
    num += 1

    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dr[i]
            ny = y + dc[i]
            if nx < 0 or ny < 0 or nx >= N or ny >= N:
                continue
            if M[nx][ny] == 1:
                M[nx][ny] = 0
                queue.append((nx, ny))
                cnt += 1

    return cnt


num = 0
result = []
for i in range(N):
    for j in range(N):
        if M[i][j] == 1:
            result.append(bfs(i, j))

result.sort()
print(num)
for i in range(num):
    print(result[i])