forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
design-graph-with-shortest-path-calculator.py
50 lines (43 loc) · 1.36 KB
/
design-graph-with-shortest-path-calculator.py
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
40
41
42
43
44
45
46
47
48
49
50
# Time: ctor: O(|V| + |E|)
# addEdge: O(1)
# shortestPath: O((|E| + |V|) * log|V|) = O(|E| * log|V|)
# Space: O(|E| + |V|) = O(|E|)
import heapq
# dijkstra's algorithm
class Graph(object):
def __init__(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
"""
self.__adj = [[] for _ in xrange(n)]
for edge in edges:
self.addEdge(edge)
def addEdge(self, edge):
"""
:type edge: List[int]
:rtype: None
"""
u, v, w = edge
self.__adj[u].append((v, w))
def shortestPath(self, node1, node2):
"""
:type node1: int
:type node2: int
:rtype: int
"""
def dijkstra(adj, start, target):
best = [float("inf")]*len(adj)
best[start] = 0
min_heap = [(best[start], start)]
while min_heap:
curr, u = heapq.heappop(min_heap)
if curr > best[u]:
continue
for v, w in adj[u]:
if not (curr+w < best[v]):
continue
best[v] = curr+w
heapq.heappush(min_heap, (best[v], v))
return best[target] if best[target] != float("inf") else -1
return dijkstra(self.__adj, node1, node2)