백준 2667번 단지번호붙이기

Solution

import sys

input = sys.stdin.readline

n = int(input())

board = [] * n

for _ in range(n):
    temp = list(input())
    board.append(list(map(int, temp[:-1])))

move = [(0, -1), (0, 1), (-1, 0), (1, 0)]
visited = [[False] * (n) for _ in range(n)]

answer = []


def dfs(i, j):
    global count
    count += 1
    visited[i][j] = True
    for idx in range(4):
        nx = i + move[idx][0]
        ny = j + move[idx][1]
        if 0 <= nx < n and 0 <= ny < n and not visited[nx][ny] and board[nx][ny] == 1:
            dfs(nx, ny)


count = 0

for i in range(n):
    for j in range(n):
        if not visited[i][j] and board[i][j] == 1:
            count = 0
            dfs(i, j)
            answer.append(count)

answer.sort()
print(len(answer))
for a in answer:
    print(a)