섬 연결하기 - python(programmers)

참치돌고래·2021년 8월 30일
0

알고리즘

목록 보기
22/36
post-custom-banner

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

from collections import deque

def unionParent(cycle, a,b):
    a=cycle[a]
    b=cycle[b]
    if a< b:
        cycle[b] =a
    else:
        cycle[a] = b

    return cycle


def findParent(cycle,a):
    if cycle[a] != a:
        return findParent(cycle, cycle[a])
    
    else:
        return a
    
def solution(n, costs):
    answer = 0
    cycle = [i for i in range(n)]
    costs.sort(key = lambda x : x[2])
    
    
    cnt =0
    
    for start, end, cost in costs:
        if cnt == n-1:
            break
            
        start=findParent(cycle,start)
        end=findParent(cycle,end)
        
        if start != end:
            unionParent(cycle, start, end)
            cnt +=1
            answer +=cost
        elif start == end:
            continue
        
        
        
            
            
        
        
        
    return answer
profile
안녕하세요
post-custom-banner

0개의 댓글