Skip to content

shortest-path ​

Guide: /guide/algorithms/graph/shortest-path

Signature ​

ts
shortestPath({ graph, from, to, traversalType, heuristic });

DFS here means the same fewest-edge path as BFS. Dijkstra requires every weight in the graph to be finite and non-negative. Bellman–Ford returns a path only after a finished run with no reachable negative cycle. A* uses heuristic and stops when the goal is extracted. heuristic is ignored for the other modes.

Params: ​

NameTypeRequiredDescription
graphIGraph<T>+Graph to search
fromT+Start vertex
toT+End vertex
traversalTypeEnumGraphTraversalType+BFS, DFS (BFS alias), DIJKSTRA, BELLMAN_FORD, or A_STAR
heuristic(vertex: T, goal: T) => numberUsed by A_STAR. Defaults to zero

Returns: ​

Array<T> ​

Throws: ​

IsNotFoundException when a vertex does not exist ​

IllegalStateException when there is no path, or Bellman–Ford finds a reachable negative cycle ​

IllegalArgumentException when a weight, heuristic, or finite sum is invalid ​

MIT Licensed