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

Function shortestPath

kotlin/Graphs/ShortestPath.kt:3–36  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import java.util.PriorityQueue
2
3fun shortestPath(n: Int, edges: List<List<Int>>, start: Int): List<Int> {
4 val graph = hashMapOf<Int, MutableList<Pair<Int, Int>>>()
5 val distances = MutableList(n) { Int.MAX_VALUE }
6 distances[start] = 0
7 // Represent the graph as an adjacency list.
8 for ((u, v, w) in edges) {
9 graph.computeIfAbsent(u) { mutableListOf() }.add(v to w)
10 graph.computeIfAbsent(v) { mutableListOf() }.add(u to w)
11 }
12 val minHeap = PriorityQueue<Pair<Int, Int>>(compareBy { it.first })
13 minHeap.add(0 to start) // (distance, node)
14 // Use Dijkstra's algorithm to find the shortest path between the start node
15 // and all other nodes.
16 while (minHeap.isNotEmpty()) {
17 val (currDist, currNode) = minHeap.poll()
18 // If the current distance to this node is greater than the recorded
19 // distance, we've already found the shortest distance to this node.
20 if (currDist > distances[currNode]) {
21 continue
22 }
23 // Update the distances of the neighboring nodes.
24 for ((neighbor, weight) in graph[currNode] ?: emptyList()) {
25 val neighborDist = currDist + weight
26 // Only update the distance if we find a shorter path to this
27 // neighbor.
28 if (neighborDist < distances[neighbor]) {
29 distances[neighbor] = neighborDist
30 minHeap.add(neighborDist to neighbor)
31 }
32 }
33 }
34 // Convert all infinity values to -1, representing unreachable nodes.
35 return distances.map { if (it == Int.MAX_VALUE) -1 else it }
36}

Callers

nothing calls this directly

Calls 1

addMethod · 0.45

Tested by

no test coverage detected