Skip to content

Commit a0b8b20

Browse files
committedNov 11, 2023
"Design Graph With Shortest Path Calculator" solution
1 parent 13d85a2 commit a0b8b20

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
 
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import heapq
2+
import sys
3+
from collections import defaultdict
4+
5+
6+
class Graph:
7+
def __init__(self, n: int, edges: list[list[int]]) -> None:
8+
self.n = n
9+
self.costs: dict[tuple[int, int], int] = {}
10+
self.conns: dict[int, list[int]] = defaultdict(list)
11+
12+
for a, b, cost in edges:
13+
self.costs[(a, b)] = cost
14+
self.conns[a].append(b)
15+
16+
def addEdge(self, edge: list[int]) -> None:
17+
a, b, cost = edge
18+
self.costs[(a, b)] = cost
19+
self.conns[a].append(b)
20+
21+
def shortestPath(self, node1: int, node2: int) -> int:
22+
heap = [(0, node1)]
23+
cost_for_node = [sys.maxsize] * self.n
24+
cost_for_node[node1] = 0
25+
26+
while heap:
27+
cost_for_far, a = heapq.heappop(heap)
28+
29+
if a == node2:
30+
return cost_for_far
31+
32+
if cost_for_far > cost_for_node[a]:
33+
continue
34+
35+
for b in self.conns[a]:
36+
new_cost = cost_for_far + self.costs[(a, b)]
37+
38+
if new_cost < cost_for_node[b]:
39+
cost_for_node[b] = new_cost
40+
heapq.heappush(heap, (new_cost, b))
41+
42+
return -1
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from src.design_graph_with_shortest_path_calculator import Graph
2+
3+
4+
def test_graph():
5+
g = Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]])
6+
7+
assert g.shortestPath(3, 2) == 6
8+
assert g.shortestPath(0, 3) == -1
9+
10+
g.addEdge([1, 3, 4])
11+
12+
assert g.shortestPath(0, 3) == 6

0 commit comments

Comments
 (0)
Please sign in to comment.