Shortest path algorithm
Find the shortest path between two vertices.
traversalType: DFS inside shortestPath is the unweighted BFS path (fewest edges). The graph iterator named DFS is a separate depth-first walk. Dijkstra rejects a negative, NaN, or infinite weight anywhere in the graph before the search starts.
Bellman–Ford accepts a finite negative weight and runs until the search finishes, even when from and to are the same. The path is available only after that. A reachable negative cycle throws IllegalStateException. A* takes an optional heuristic. Omitted, it is zero and the cost matches Dijkstra. The walk stops when the goal is extracted. Preparing A* reads every vertex and every directed arc, O(V + E), before the first step.
Guides: Bellman–Ford, A*.
Import
import {
DirectedGraph,
EnumGraphTraversalType,
shortestPath,
} from "@apexds/core";API reference
API: /api/algorithms/graph/shortest-path
Example usage in a weighted graph (Dijkstra)
import {
DirectedGraph,
EnumGraphTraversalType,
shortestPath,
} from "@apexds/core";
const graph = new DirectedGraph<string>();
graph
.addVertex("Mike")
.addVertex("Bob")
.addVertex("Lisa")
.addVertex("Aaron")
.addVertex("James")
.addVertex("Anna")
.addEdge("Mike", "Bob", 5)
.addEdge("Mike", "Lisa", 3)
.addEdge("Lisa", "Aaron", 3)
.addEdge("Lisa", "James", 3)
.addEdge("James", "Aaron", 3)
.addEdge("James", "Anna", 6)
.addEdge("Bob", "Anna", 15);
shortestPath({
graph,
from: "Mike",
to: "Anna",
traversalType: EnumGraphTraversalType.DIJKSTRA,
});
// ["Mike", "Lisa", "James", "Anna"]Example usage in an unweighted graph (BFS)
import {
DirectedGraph,
EnumGraphTraversalType,
shortestPath,
} from "@apexds/core";
const graph = new DirectedGraph<string>();
graph
.addVertex("Mike")
.addVertex("Bob")
.addVertex("Lisa")
.addVertex("Aaron")
.addVertex("James")
.addVertex("Anna")
.addEdge("Mike", "Bob")
.addEdge("Mike", "Aaron")
.addEdge("Mike", "Lisa")
.addEdge("Lisa", "James")
.addEdge("Lisa", "Aaron")
.addEdge("James", "Aaron")
.addEdge("James", "Anna")
.addEdge("Aaron", "Anna");
shortestPath({
graph,
from: "Mike",
to: "Anna",
traversalType: EnumGraphTraversalType.BFS,
});
// ["Mike", "Aaron", "Anna"]