[알고리즘] 백준 2667 단지번호붙이기

CHOI IN HO·2024년 1월 24일
0

코딩테스트

목록 보기
43/74

풀이

dfs 통해서 연결되어 있는것끼리 방문을 했고, 만약 연결되어 있다면 숫자를 동일한걸로 바꿔주었다.

from collections import deque

N = int(input())

graph = []
result = []
for i in range(N):
    graph.append(list(map(int, input())))


cnt = 0
def dfs(x, y,s):
    global cnt
    if x < 0 or y < 0 or x >=N or y >= N:
        return

    if graph[x][y] == 1:
        graph[x][y] = s
        dfs(x+1, y,s)
        dfs(x-1, y,s)
        dfs(x, y+1,s)
        dfs(x, y-1,s)
        return True

t= 2
for i in range(N):
    for j in range(N):
        if dfs(i, j, t) == True:
            cnt+=1
            t+=1
for i in range(2, t):
    s = 0
    for k in graph:
        if i in k:
            s += k.count(i)
    result.append(s)


print(cnt)
result.sort()
for i in range(len(result)):
    print(result[i])
profile
개발자기 되기 위해선 무엇이든!

0개의 댓글