|
| 1 | +import { IGraph } from './0-undirected-graph'; |
| 2 | + |
| 3 | +export interface IPath { |
| 4 | + nodeList: string[]; |
| 5 | + distance: number; |
| 6 | +} |
| 7 | + |
| 8 | +export function dijkstraShortestPath( |
| 9 | + graph: IGraph, |
| 10 | + sourceNode: string, |
| 11 | + destinationNode: string, |
| 12 | +): IPath { |
| 13 | + const edges = new Set(graph.edges); |
| 14 | + const distanceTo = graph.nodes |
| 15 | + .reduce( |
| 16 | + (result, node) => ( |
| 17 | + result[node] = { |
| 18 | + from: null, |
| 19 | + distance: node === sourceNode ? 0 : Number.MAX_SAFE_INTEGER, |
| 20 | + }, |
| 21 | + result |
| 22 | + ), |
| 23 | + {} as { [ dest: string ]: { from: string | null, distance: number } } |
| 24 | + ); |
| 25 | + |
| 26 | + const unvisited = new Set(graph.nodes); |
| 27 | + |
| 28 | + let currentNode: string | undefined = sourceNode; |
| 29 | + do { |
| 30 | + unvisited.delete(currentNode); |
| 31 | + |
| 32 | + for (let edge of edges) |
| 33 | + if (edge.source === currentNode || edge.destination === currentNode) { |
| 34 | + edges.delete(edge); |
| 35 | + |
| 36 | + const neighbor = edge.source === currentNode ? edge.destination : edge.source; |
| 37 | + const alternativeDistance = distanceTo[currentNode].distance + edge.distance; |
| 38 | + |
| 39 | + if (alternativeDistance < distanceTo[neighbor].distance) { |
| 40 | + distanceTo[neighbor] = { from: currentNode, distance: alternativeDistance }; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + // current = unvisited node with shortest `distance` path to it |
| 45 | + let closestUnvisitedEntry = (Object |
| 46 | + .entries(distanceTo) |
| 47 | + .sort((entry1, entry2) => entry1["1"].distance - entry2["1"].distance) |
| 48 | + .find(entry => unvisited.has(entry["0"]))); |
| 49 | + currentNode = closestUnvisitedEntry && closestUnvisitedEntry["0"]; |
| 50 | + |
| 51 | + } while (currentNode); |
| 52 | + |
| 53 | + return { |
| 54 | + distance: distanceTo[destinationNode].distance, |
| 55 | + nodeList: unwindPath(distanceTo, destinationNode), |
| 56 | + }; |
| 57 | +} |
| 58 | + |
| 59 | +export function unwindPath( |
| 60 | + distanceTo: { [dest: string]: { from: string | null, distance: number } }, |
| 61 | + destinationNode: string, |
| 62 | +) { |
| 63 | + const path: string[] = [ destinationNode ]; |
| 64 | + let currentNode: string | null = destinationNode; |
| 65 | + do { |
| 66 | + const entry: { from: string | null, distance: number } = distanceTo[currentNode]; |
| 67 | + currentNode = entry.from; |
| 68 | + if (currentNode) path.unshift(currentNode); |
| 69 | + } while (currentNode); |
| 70 | + return path; |
| 71 | +} |
0 commit comments