백준 | 단지번호붙이기

jeonghens·2024년 11월 18일

알고리즘: BOJ

목록 보기
89/125

백준 단지번호붙이기



import sys
from collections import deque


def bfs(graph, x, y, n):
    queue = deque()
    queue.append((x, y))
    graph[x][y] = 0
    cnt = 1

    dx = [-1, 1, 0, 0]
    dy = [0, 0, -1, 1]

    while queue:
        x, y = queue.popleft()
        
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            if 0 <= nx < n and 0 <= ny < n:
                if graph[nx][ny] == 1:
                    graph[nx][ny] = 0
                    queue.append((nx, ny))
                    cnt += 1

    return cnt


n = int(sys.stdin.readline().strip())

graph = [list(map(int, sys.stdin.readline().strip())) for _ in range(n)]

complexes = []
for i in range(n):
    for j in range(n):
        if graph[i][j] == 1:
            house_cnt = bfs(graph, i, j, n)
            complexes.append(house_cnt)

# 조건에 맞게 출력하기 위해 오름차순 정렬이 필요함!
complexes.sort()
print(len(complexes))
print('\n'.join(map(str, complexes)))
profile
알고리즘이나 SQL 문제 풀이를 올리고 있습니다. 피드백 환영합니다!

0개의 댓글