-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0743-network-delay-time.py
More file actions
39 lines (34 loc) · 1.05 KB
/
0743-network-delay-time.py
File metadata and controls
39 lines (34 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# time complexity: O(n + elogn)
# space complexity: O(n+e)
from collections import defaultdict
from heapq import heapify, heappop, heappush
from typing import List
class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
seen = set()
adjList = defaultdict(list)
for outNode, inNode, time in times:
adjList[outNode].append((inNode, time))
minHeap = [(0, k)]
heapify(minHeap)
while minHeap:
currTime, currNode = heappop(minHeap)
seen.add(currNode)
if len(seen) == n:
return currTime
for neighbor, time in adjList[currNode]:
if neighbor not in seen:
heappush(minHeap, (time + currTime, neighbor))
return -1
times = [[2, 1, 1], [2, 3, 1], [3, 4, 1]]
n = 4
k = 2
print(Solution().networkDelayTime(times, n, k))
times = [[1, 2, 1]]
n = 2
k = 1
print(Solution().networkDelayTime(times, n, k))
times = [[1, 2, 1]]
n = 2
k = 2
print(Solution().networkDelayTime(times, n, k))