chyam

[프로그래머스 Lv3,python] - 네트워크 본문

프로그래머스/LV3

[프로그래머스 Lv3,python] - 네트워크

chyam_eun 2026. 4. 27. 14:50

https://school.programmers.co.kr/learn/courses/30/lessons/43162

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

def solution(n, computers):
    parent = [i for i in range(n)]
    rank = [0] * n

    def find(x):
        if parent[x] != x:
            parent[x] = find(parent[x])
        return parent[x]

    def union(x, y):
        x = find(x)
        y = find(y)

        if rank[x] < rank[y]: # 높이가 더 높은쪽에 붙임
            parent[x] = y
        elif rank[x] > rank[y]: # 높이가 더 높은쪽에 붙임
            parent[y] = x
        else: # 높이가 같음. 암데나 붙임
            parent[y] = x
            rank[x] += 1

    for i in range(len(computers)):
        for j in range(len(computers[0])):
            if i != j and computers[i][j] == 1:
                union(i, j)

    return len(set(parent))