@@ -3,7 +3,7 @@ import { PriorityQueue } from '../data/PriorityQueue.js';
3
3
/** @typedef {import('../graph').Graph } Graph */
4
4
/** @typedef {import('../types').Edge } Edge */
5
5
/** @typedef {import('../types').NodeIdentifier } NodeIdentifier */
6
- /** @typedef {import('../types').FloydWarshallItem } FloydWarshallItem */
6
+ /** @typedef {import('../types').NodePath } NodePath */
7
7
8
8
const DEFAULT_WEIGHT_FUNC = ( ) => 1 ;
9
9
@@ -13,14 +13,14 @@ const DEFAULT_WEIGHT_FUNC = () => 1;
13
13
* @param {string } source
14
14
* @param {(edge: Edge) => number } weightFn
15
15
* @param {(v: NodeIdentifier) => Edge[] } edgeFn
16
- * @returns {Record<NodeIdentifier, FloydWarshallItem > }
16
+ * @returns {Record<NodeIdentifier, NodePath > }
17
17
*/
18
18
function runDijkstra ( g , source , weightFn , edgeFn ) {
19
- /** @type {Record<NodeIdentifier, FloydWarshallItem > } */
19
+ /** @type {Record<NodeIdentifier, NodePath > } */
20
20
const results = { } ;
21
21
const pq = new PriorityQueue ( ) ;
22
22
let v ;
23
- /** @type FloydWarshallItem */
23
+ /** @type NodePath */
24
24
let vEntry ;
25
25
26
26
/**
@@ -64,11 +64,22 @@ function runDijkstra(g, source, weightFn, edgeFn) {
64
64
}
65
65
66
66
/**
67
- * @param {Graph } g
68
- * @param {NodeIdentifier } source
69
- * @param {((edge: Edge) => number)= } weightFn
70
- * @param {((v: NodeIdentifier) => Edge[])= } edgeFn
71
- * @returns {Record<NodeIdentifier, FloydWarshallItem> }
67
+ * This function is an implementation of Dijkstra's algorithm which finds the shortest
68
+ * path from source to all other nodes in graph. This function returns a map of
69
+ * v -> { distance, predecessor }. The distance property holds the sum of the weights
70
+ * from source to v along the shortest path or Number.POSITIVE_INFINITY if there is no path
71
+ * from source. The predecessor property can be used to walk the individual elements of the
72
+ * path from source to v in reverse order.
73
+ * Complexity: O((|E| + |V|) * log |V|).
74
+ *
75
+ * @param {Graph } g - graph where to search paths.
76
+ * @param {NodeIdentifier } source node to start paths from.
77
+ * @param {((edge: Edge) => number)= } weightFn function which takes edge e and returns the weight of it. If no weightFn
78
+ * is supplied then each edge is assumed to have a weight of 1. This function throws an
79
+ * Error if any of the traversed edges have a negative edge weight.
80
+ * @param {((v: NodeIdentifier) => Edge[])= } edgeFn function which takes a node v and returns the ids of all edges incident to it
81
+ * for the purposes of shortest path traversal. By default this function uses the graph.outEdges.
82
+ * @returns {Record<NodeIdentifier, NodePath> } shortest paths map that starts from node source
72
83
*/
73
84
export default function dijkstra ( g , source , weightFn , edgeFn ) {
74
85
return runDijkstra ( g , String ( source ) , weightFn || DEFAULT_WEIGHT_FUNC , edgeFn || ( v => g . outEdges ( v ) ) ) ;
0 commit comments