use pathfinding_indexed::IndexedGraph;
fn main() {
const NODE_NAMES: [char; 5] = ['A', 'B', 'C', 'D', 'E'];
let adjacency_matrix: Vec<Vec<Option<u32>>> = vec![
vec![None, Some(4), Some(2), None, None], vec![None, None, Some(1), Some(5), None], vec![None, None, None, Some(8), Some(10)], vec![None, None, None, None, Some(2)], vec![None, None, None, None, None], ];
let adjacency = adjacency_matrix
.iter()
.map(|row| {
row.iter()
.enumerate()
.filter_map(|(neighbor, weight)| weight.map(|w| (neighbor, w)))
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
let graph = IndexedGraph::from_adjacency(adjacency);
let heuristic = |node: usize| -> u32 {
u32::from(node != 4)
};
let result = graph.astar(0, heuristic, |node| node == 4);
match result {
Some((path, cost)) => {
let path_names: Vec<char> = path.iter().map(|&i| NODE_NAMES[i]).collect();
println!("Shortest path from A to E using A*:");
println!(" Path (indices): {path:?}");
println!(" Path (names): {path_names:?}");
println!(" Total cost: {cost}");
assert_eq!(path, vec![0, 1, 3, 4]);
assert_eq!(cost, 11);
}
None => println!("No path found"),
}
let result2 = graph.astar(1, heuristic, |node| node == 4);
match result2 {
Some((path, cost)) => {
let path_names: Vec<char> = path.iter().map(|&i| NODE_NAMES[i]).collect();
println!("\nShortest path from B to E:");
println!(" Path (indices): {path:?}");
println!(" Path (names): {path_names:?}");
println!(" Total cost: {cost}");
}
None => println!("No path found"),
}
println!("\nExample completed successfully!");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_adjacency_matrix_example() {
main();
}
}