๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐‘†๐‘ข๐‘›๐‘ โ„Ž๐‘–๐‘›๐‘’ ๐‘Ž๐‘“๐‘ก๐‘’๐‘Ÿ ๐‘Ÿ๐‘Ž๐‘–๐‘›โœง

[Python] ๋ฐฑ์ค€ 1012 & ๋ฐฑ์ค€ 2667 ๋ณธ๋ฌธ

#๋ฐฑ์ค€ 1012 ์œ ๊ธฐ๋† ๋ฐฐ์ถ”

import sys
from collections import deque

input = sys.stdin.readline

d_row = [0, -1, 0, 1]
d_col = [1, 0, -1, 0]

def bfs(start_node):
    queue = deque()
    queue.append(start_node)
    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + d_row[i]
            ny = y + d_col[i]
            if nx < 0 or ny < 0 or nx > n-1 or ny > m-1:
                continue
            if graph[nx][ny] == 0:
                continue
            queue.append([nx, ny])
            graph[nx][ny] = 0


t = int(input())

for _ in range(t):
    m, n, k = map(int, input().split())  # m = ๊ฐ€๋กœ(์—ด), n = ์„ธ๋กœ(ํ–‰)
    graph = [[0] * m for _ in range(n)]

    for _ in range(k):
        y, x = map(int, input().split())
        graph[x][y] = 1

    cnt = 0
    for i in range(n):
        for j in range(m):
            if graph[i][j] == 1:
                bfs([i, j])
                cnt += 1
    print(cnt)
#๋ฐฑ์ค€ 2667

from collections import deque

n = int(input())
graph = []
for _ in range(n):
    graph.append(list(map(int, input())))

d_row = [0, -1, 0, 1]
d_col = [1, 0, -1, 0]

def bfs(x,y):
    queue = deque()
    queue.append([x,y])
    graph[x][y] = 0
    cnt = 1
    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x+ d_row[i]
            ny = y + d_col[i]
            if nx<0 or ny < 0 or nx > n -1 or ny > n-1:
                continue
            if graph[nx][ny] == 0:
                continue
            queue.append([nx,ny])
            graph[nx][ny] = 0
            cnt += 1

    return cnt

num = 0
answer_list = []
for i in range(n):
    for j in range(n):
        if graph[i][j] == 1:
            num += 1
            answer = bfs(i, j)
            answer_list.append(answer)

print(num)
answer_list.sort()
for i in answer_list:
    print(i)