백준 2667 단지번호붙이기
나의 답
import sys
from collections import deque
N = int(sys.stdin.readline())
graph = [[i for i in list(map(int, sys.stdin.readline().rstrip()))] for _ in range(N)]
q = deque()
stack = []
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def bfs(x, y):
q = deque([(x, y)])
graph[x][y] = 0
cnt = 1
while q:
prev_x, prev_y = q.popleft()
for i in range(4):
next_x, next_y = prev_x + dx[i], prev_y + dy[i]
if 0 <= next_x < N and 0 <= next_y < N:
if graph[next_x][next_y] == 1:
q.append((next_x, next_y))
graph[next_x][next_y] = 0
cnt += 1
return cnt
for i in range(N):
for j in range(N):
if graph[i][j] == 0:
continue
else:
stack.append(bfs(i, j))
print(len(stack))
print(*sorted(stack), sep='\n')