Skip to main content

get_shortest_path_astar

Function get_shortest_path_astar 

Source
pub fn get_shortest_path_astar(
    graph: &Graph,
    from: VertexId,
    to: VertexId,
    weights: Option<&[f64]>,
    mode: DijkstraMode,
    heuristic: Option<&AstarHeuristic<'_>>,
) -> IgraphResult<ShortestPath>
Expand description

Calculate a single shortest path from from to to using A*.

Returns the path as both its vertex sequence (source first, target last) and the edge sequence along it. If several shortest paths exist, an arbitrary one is returned. The path is empty when to is unreachable; when from == to the vertex sequence is [from] and the edge sequence is empty.

weights are optional edge weights; None treats every edge as weight 1 (an unweighted graph). All weights must be non-negative and non-NaN; positive-infinite weights mark unusable edges. On directed graphs mode selects the followed adjacency (DijkstraMode::Out / DijkstraMode::In / DijkstraMode::All); it is ignored on undirected graphs.

heuristic, if given, estimates the remaining distance from a candidate vertex to to. It must be admissible (never overestimate) for the returned path to be a true shortest path. None uses the null heuristic (always 0), making A* equivalent to Dijkstra.

§Errors

Returns IgraphError::VertexOutOfRange if from or to is not a valid vertex, or IgraphError::InvalidArgument if weights is provided and its length differs from the edge count, contains NaN, or contains a negative value.

§Examples

use rust_igraph::{Graph, get_shortest_path_astar, DijkstraMode};

let mut g = Graph::new(4, false).unwrap();
g.add_edge(0, 1).unwrap(); // edge 0
g.add_edge(1, 2).unwrap(); // edge 1
g.add_edge(2, 3).unwrap(); // edge 2

// Null heuristic (None) behaves exactly like Dijkstra.
let p = get_shortest_path_astar(&g, 0, 3, None, DijkstraMode::Out, None).unwrap();
assert_eq!(p.vertices, vec![0, 1, 2, 3]);
assert_eq!(p.edges, vec![0, 1, 2]);

// An admissible heuristic (here: |target - v|, a lower bound on the
// number of hops) yields the same shortest path.
let h = |v: u32, to: u32| f64::from(to.abs_diff(v));
let q = get_shortest_path_astar(&g, 0, 3, None, DijkstraMode::Out, Some(&h)).unwrap();
assert_eq!(q.vertices, vec![0, 1, 2, 3]);