강의

멘토링

커뮤니티

Inflearn Community Q&A

tmdtjs's profile image
tmdtjs

asked

Coding Test [ ALL IN ONE ]

[Apply code] 👉 [Network Delay Time] (Second half)

defaultdict() 함수의 선언부가 궁금해요

Resolved

Written on

·

262

1

다익스트라 Network Delay Time 강의에

가중치 그래프 구현을 위해 사용된

defalutdict() 함수의 내용이 없네요 어떻게 선언하셨는지 궁금합니다.

python코딩-테스트알고리즘

Answer 1

1

nossi님의 프로필 이미지
nossi
Instructor

안녕하세요 동찬님.

 

문제에서 나온 코드 구현 부분은 조금 생략한 부분이 있습니다.

그래서 노션에 적어두었는데, 혹시 이걸 말씀하신게 맞을 까

from collections import defaultdict
import heapq


class Solution(object):
    def networkDelayTime(self, times, n, k):
        graph = defaultdict(list)
        for time in times:
            graph[time[0]].append((time[2], time[1]))

        costs = {}
        pq = []
        heapq.heappush(pq, (0, k))

        while pq:
            cur_cost, cur_node = heapq.heappop(pq)
            if cur_node not in costs:
                costs[cur_node] = cur_cost
                for cost, next_node in graph[cur_node]:
                    next_cost = cur_cost + cost
                    heapq.heappush(pq, (next_cost, next_node))

        for i in range(1, n + 1):
            if i not in costs:
                return -1

        return max(costs.values())


times = [[2, 1, 1], [2, 3, 1], [3, 4, 1]]
n = 4
k = 2

s = Solution()
print(s.networkDelayTime(times, n, k))
tmdtjs's profile image
tmdtjs

asked

Ask a question