pub fn astar<'a, G, NI, V, OS, CF, GS, H>(
graph: &G,
start: NI,
goal: NI,
heuristic: H,
open_set: OS,
came_from: CF,
g_score: GS,
path_buffer: &'a mut [NI],
) -> Result<Option<&'a [NI]>, AlgorithmError<NI>>where
G: GraphWithEdgeValues<NI, V>,
NI: NodeIndex,
OS: MapTrait<NI, V>,
CF: MapTrait<NI, NI>,
GS: MapTrait<NI, Option<V>>,
H: Fn(NI, NI) -> V,
V: PartialOrd + Copy + Add<Output = V> + Default,
AlgorithmError<NI>: From<G::Error>,Expand description
A* pathfinding algorithm to find shortest path between two specific nodes
Finds the shortest path from a start node to a goal node using a heuristic function to guide the search. The heuristic must be admissible (never overestimate the actual cost) for A* to guarantee optimal results.
§Arguments
graph- Graph implementing GraphWithEdgeValuesstart- Starting nodegoal- Goal node to find path toheuristic- Heuristic function estimating cost from any node to goalopen_set- Map to track nodes in the open set with their f-scorescame_from- Map to track the path (parent of each node)g_score- Map to store actual cost from start to each nodepath_buffer- Buffer to store the reconstructed path
§Returns
Ok(Some(path_slice))if path found, containing the path from start to goalOk(None)if no path existsErr(AlgorithmError)if the operation fails
§Heuristic Function
The heuristic function should estimate the cost from a node to the goal. For optimal results, it must be admissible (never overestimate) and consistent (satisfy triangle inequality).
§Example
use heapless_graphs::algorithms::astar;
use heapless_graphs::containers::maps::{staticdict::Dictionary, MapTrait};
use heapless_graphs::edgelist::edge_list::EdgeList;
use heapless_graphs::edges::EdgeValueStruct;
// Create a simple graph: 0 --(2)--> 1 --(3)--> 2
let edge_data = EdgeValueStruct([(0usize, 1usize, 2i32), (1, 2, 3)]);
let graph = EdgeList::<8, _, _>::new(edge_data);
// Simple heuristic that returns 0 (converts A* to Dijkstra)
let heuristic = |_node: usize, _goal: usize| 0i32;
let open_set = Dictionary::<usize, i32, 16>::new();
let came_from = Dictionary::<usize, usize, 16>::new();
let g_score = Dictionary::<usize, Option<i32>, 16>::new();
let mut path_buffer = [0usize; 16];
let result = astar(&graph, 0, 2, heuristic, open_set, came_from, g_score, &mut path_buffer).unwrap();
assert!(result.is_some());
let path = result.unwrap();
assert_eq!(path, &[0, 1, 2]);