( graph: [number, number][][], start: number )
| 11 | * @see https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm |
| 12 | */ |
| 13 | export const dijkstra = ( |
| 14 | graph: [number, number][][], |
| 15 | start: number |
| 16 | ): number[] => { |
| 17 | // We use a priority queue to make sure we always visit the closest node. The |
| 18 | // queue makes comparisons based on path weights. |
| 19 | const priorityQueue = new PriorityQueue( |
| 20 | (a: [number, number]) => { |
| 21 | return a[0] |
| 22 | }, |
| 23 | graph.length, |
| 24 | (a: [number, number], b: [number, number]) => { |
| 25 | return a[1] < b[1] |
| 26 | } |
| 27 | ) |
| 28 | priorityQueue.insert([start, 0]) |
| 29 | // We save the shortest distance to each node in `distances`. If a node is |
| 30 | // unreachable from the start node, its distance is Infinity. |
| 31 | const distances = Array(graph.length).fill(Infinity) |
| 32 | distances[start] = 0 |
| 33 | |
| 34 | while (priorityQueue.size() > 0) { |
| 35 | const node = priorityQueue.extract()[0] |
| 36 | graph[node].forEach(([child, weight]) => { |
| 37 | const new_distance = distances[node] + weight |
| 38 | if (new_distance < distances[child]) { |
| 39 | // Found a new shortest path to child node. Record its distance and add child to the queue. |
| 40 | // If the child already exists in the queue, the priority will be updated. This will make sure the queue will be at most size V (number of vertices). |
| 41 | priorityQueue.increasePriority(child, [child, weight]) |
| 42 | distances[child] = new_distance |
| 43 | } |
| 44 | }) |
| 45 | } |
| 46 | |
| 47 | return distances |
| 48 | } |
no test coverage detected