Skip to content

A* ​

aStar(graph, start, end, heuristic) searches for a shortest path using one i32 heuristic value per vertex. An admissible heuristic preserves optimality; the input may be an adjacency list or Graph<N, i32>.

SignatureReturnsComplexity
aStar(adj: [usize, i32][][], start: usize, end: usize, heuristic: i32[])[usize[], i32]?O((V + E) log V)
tyrus
import { aStar } from "tyrus:algorithm";

const result: [usize[], i32]? = aStar([[[1, 4], [2, 2]], [[3, 5]], [[3, 1]], []], 0, 3, [3, 1, 1, 0]);
if (result) { print(result[1]); } // 3

Study result ​

aStarInfo exposes distances, predecessors, relaxations, heuristic evaluations, opened and closed vertices, and the final cost when the destination is reached.

tyrus
interface AStarInfo {
    distances: i32[];
    predecessors: usize?[];
    relaxationCount: usize;
    processedVertexCount: usize;
    examinedEdgeCount: usize;
    heuristicEvaluationCount: usize;
    openedVertexCount: usize;
    closedVertexCount: usize;
    finalCost: i32?;
}
tyrus
import { AStarInfo, ShortestPathInfo, aStarInfo } from "tyrus:algorithm";

const info: AStarInfo = aStarInfo([[[1, 4], [2, 1]], [[3, 1]], [[1, 2], [3, 5]], []], 0, 3, [3, 1, 2, 0]);
print(info.distances); // [0, 3, 1, 4]
print(info.predecessors[3] ?? 99); // 1
print(info.relaxationCount); // 5
print(info.processedVertexCount); // 4
print(info.examinedEdgeCount); // 5
print(info.heuristicEvaluationCount); // 6
print(info.openedVertexCount); // 4
print(info.closedVertexCount); // 4
print(info.finalCost ?? -1); // 4