Skip to content

Graph iterator A* ​

Shortest path for finite weights >= 0 and a consistent heuristic. The queue stores g, the best cost from the start. An entry's priority is g + h. A worse entry is left in the queue and skipped. The walk stops when the goal is extracted.

Read full: Berkeley CS 188, A*

Import ​

ts
import {
  DirectedGraph,
  EnumGraphTraversalType,
  createGraphIterator,
  shortestPath,
} from "@apexds/core";

API reference ​

API: /api/algorithms/graph/iterator-a-star

When the path is ready ​

current() and the following next() name the same vertex. Repeated current() and hasNext() do not advance the search. A vertex's distance is final when that vertex is extracted. getPath is then allowed for it, even if the goal has not been extracted yet. After the goal is extracted, the walk stops. An empty queue means the goal cannot be reached, and getPath throws IllegalStateException.

A literal A_STAR factory call requires to, including createGraphIterator<T>(graph, A_STAR). A dynamic mode with that same explicit vertex type is createGraphIterator<T>(graph, mode, { to }). The property must be present even when the vertex is undefined. The heuristic is (vertex, goal) => number. Omitted, it returns zero, and the path cost matches Dijkstra when every compared sum is exact.

The run copies the graph before the first step, including a new vertex array. A later edit of the graph, or of the array returned by vertices(), is invisible until the next initIterator. A rejected init does not erase the previous path.

Heuristic check ​

Before the search, and before the previous run is replaced, A* stores h(vertex, goal) once per vertex and checks every directed arc. An undirected edge is checked in both directions. The check rejects a non-finite or negative weight, a non-finite or negative heuristic, h(goal, goal) !== 0, and h(u) > weight(u, v) + h(v). That preparation is O(V + E) even when the goal is one edge away. g + weight, g + h, and weight + h must be finite and exact in IEEE-754. 10000000000000000 + 3 is not exact, so it cannot tie with a direct edge of weight 10000000000000004. Overflow or an inexact sum during the walk throws IllegalArgumentException, and that run keeps throwing it until the next initIterator. A failed check of weight + h happens first and leaves the previous path in place.

With the snapshot, the queue may hold one entry per improvement, up to O(E), and the walk is O(V + E log(E + 1)).

Example ​

ts
const graph = new DirectedGraph<string>();
graph
  .addVertex("S")
  .addVertex("A")
  .addVertex("T")
  .addEdge("S", "T", 10)
  .addEdge("S", "A", 1)
  .addEdge("A", "T", 1);

shortestPath({
  graph,
  from: "S",
  to: "T",
  traversalType: EnumGraphTraversalType.A_STAR,
  heuristic: (vertex) => (vertex === "S" ? 2 : vertex === "A" ? 1 : 0),
});
// ["S", "A", "T"], cost 2

createGraphIterator(graph, EnumGraphTraversalType.A_STAR, {
  to: "T",
});

MIT Licensed