알고리즘

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

황성안 2021. 9. 24. 00:45
728x90

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def solution(n, costs):
   
    answer = 0
    costs.sort(key=lambda x: x[2])                          
    # costs를 정렬한다(키는 익명함수 람다의 값중costs[2]의 크기순 )
    # print(costs)
    routes = set([costs[0][0]])
    
    
    while len(routes)!=n:
        print(routes)
        for i, cost in enumerate(costs):
            if cost[0] in routes and cost[1] in routes:
                continue
            if cost[0] in routes or cost[1] in routes:
                routes.update([cost[0], cost[1]])
                answer += cost[2]
                costs[i] = [-1, -1, -1]
                break
    return answer
 
cs
728x90