[백준/파이썬] 2667번

민정·2023년 4월 27일
0

[백준/파이썬]

목록 보기
136/245
post-thumbnail

📍백준 2667번 문제

https://www.acmicpc.net/problem/2667

코드

import sys
from collections import deque
input = sys.stdin.readline

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


def bfs(graph, a, b):
    queue = deque()
    queue.append((a, b))
    graph[a][b] = 0
    count = 1

    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or nx >= n or ny < 0 or ny >= n:
                continue
            if graph[nx][ny] == 1:
                graph[nx][ny] = 0
                queue.append((nx, ny))
                count += 1
    return count


n = int(input())
graph = [list(map(int, input().rstrip('\n'))) for _ in range(n)]


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

cnt.sort()
print(len(cnt))
for i in range(len(cnt)):
    print(cnt[i])

풀이

bfs를 이용해서 풀었다.

profile
パㅔバ6ㅇr 덤벼ㄹΓ :-0

0개의 댓글