[프로그래머스] 섬 연결하기

박형진·2022년 9월 29일
0

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

1. 코드

def solution(n, costs):
    answer = 0
    
    def find_parent(x):
        if parent[x] != x:
            parent[x] = find_parent(parent[x])
        return parent[x]
    
    def union(a, b):
        # 루트 노드를 가져온다
        a = find_parent(a)
        b = find_parent(b)
        if a > b:
            parent[b] = a
        else:
            parent[a] = b
    
    
    # 루트 노드를 저장하는 배열 parent
    parent = [0] * (n + 1)
    for i in range(1, n + 1):
        parent[i] = i
    
    # 거리가 짧은 순서대로 정렬
    costs = sorted(costs, key=lambda x: x[2])
    
    for cost in costs:
        a, b, weight = cost
        if find_parent(a) != find_parent(b):
            union(a, b)
            answer += weight

    return answer

2. 후기

크루스칼 알고리즘을 사용하기만 하면 풀리는 문제

profile
안녕하세요!

0개의 댓글