티스토리 뷰

in Pypy

# 2667번 단지번호붙이기
# BFS로 풀기
import sys

N = int(sys.stdin.readline())
data = []
for _ in range(N):
    data.append([int(d) for d in str(sys.stdin.readline().rstrip())])
# print(data)
queue = []
groupList = []


def bfs(row, col):
    queue.insert(0, [row, col])
    while queue:
        current = queue.pop()
        newRow = current[0]
        newCol = current[1]
        # 이웃 찾기
        for a in [-1, 1]:
            if 0 <= (newRow - a) < N:
                if data[newRow - a][newCol] == 1 and [newRow-a, newCol] not in queue:
                    queue.insert(0, [newRow - a, newCol])
        for b in [-1, 1]:
            if 0 <= (newCol - b) < N:
                if data[newRow][newCol - b] == 1 and [newRow, newCol - b] not in queue:
                    queue.insert(0, [newRow, newCol - b])
        data[newRow][newCol] = -1
        groupList[-1] += 1

for i in range(N):
    for j in range(N):
        if data[i][j] == 1:
            groupList.append(0)
            bfs(i, j)
print(len(groupList))
groupList.sort()
print(*groupList, sep='\n')
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함