문제출처: https://programmers.co.kr/learn/courses/30/lessons/42861
접근법
프림 알고리즘으로 구현하였다.
1. 임의의 노드 하나를 list T에 추가한다.
2. 모든 노드가 T에 추가될 때까지 반복( while문 )
3. 가장 cost가 낮은 연결들부터 반복문을 돌며 T에 있는 노드 , T에 있지 않는 노드를 잇는 연결만 정답에 추가한다.
코드
def solution(n, costs): answer = 0 T = [] T.append( costs[0][0] ) costs.sort(key=lambda x:x[2]) while( len(T) < n ): for index,(i,j,k) in enumerate(costs): if( (i in T) ^ (j in T) ): T.append( j if i in T else i ) costs.remove([i,j,k]) answer += k break return answer