MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / shortest_path

Function shortest_path

python3/Graphs/shortest_path.py:6–32  ·  view source on GitHub ↗
(n: int, edges: List[int], start: int)

Source from the content-addressed store, hash-verified

4
5
6def shortest_path(n: int, edges: List[int], start: int) -> List[int]:
7 graph = defaultdict(list)
8 distances = [float('inf')] * n
9 distances[start] = 0
10 # Represent the graph as an adjacency list.
11 for u, v, w in edges:
12 graph[u].append((v, w))
13 graph[v].append((u, w))
14 min_heap = [(0, start)] # (distance, node)
15 # Use Dijkstra's algorithm to find the shortest path between the start node
16 # and all other nodes.
17 while min_heap:
18 curr_dist, curr_node = heapq.heappop(min_heap)
19 # If the current distance to this node is greater than the recorded
20 # distance, we've already found the shortest distance to this node.
21 if curr_dist > distances[curr_node]:
22 continue
23 # Update the distances of the neighboring nodes.
24 for neighbor, weight in graph[curr_node]:
25 neighbor_dist = curr_dist + weight
26 # Only update the distance if we find a shorter path to this
27 # neighbor.
28 if neighbor_dist < distances[neighbor]:
29 distances[neighbor] = neighbor_dist
30 heapq.heappush(min_heap, (neighbor_dist, neighbor))
31 # Convert all infinity values to -1, representing unreachable nodes.
32 return [-1 if dist == float('inf') else dist for dist in distances]

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected