-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path2642-design-graph-with-shortest-path-calculator.py
More file actions
36 lines (30 loc) · 1.14 KB
/
2642-design-graph-with-shortest-path-calculator.py
File metadata and controls
36 lines (30 loc) · 1.14 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
#time complexity: O(n+m *(v+elogv))
#space complexity: O(e+v+n)
from typing import List
from heapq import heappop, heappush
from math import inf
class Graph:
def __init__(self, n: int, edges: List[List[int]]):
self.adjList = [[] for _ in range(n)]
for fromNode, toNode, cost in edges:
self.adjList[fromNode].append((toNode, cost))
def addEdge(self, edge: List[int]) -> None:
fromNode, toNode, cost = edge
self.adjList[fromNode].append((toNode, cost))
def shortestPath(self, node1: int, node2: int) -> int:
n = len(self.adjList)
pq = [(0, node1)]
costForNode = [inf] * (n)
costForNode[node1] = 0
while pq:
currCost, currNode = heappop(pq)
if currCost > costForNode[currNode]:
continue
if currNode == node2:
return currCost
for neighbor, cost in self.adjList[currNode]:
newCost = currCost + cost
if newCost < costForNode[neighbor]:
costForNode[neighbor] = newCost
heappush(pq, (newCost, neighbor))
return -1