Algorithm/noj.am
[Python] 백준 2667번 - 단지번호붙이기
SweetDev
2021. 1. 26. 06:06
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')