Here is a Rust program that implements the A* search algorithm to find the cheapest path between two nodes in a graph:
rust
use std::collections::BinaryHeap;
// Node in the graph
struct Node {
id: usize,
neighbors: Vec<Node>,
distance: usize,
}
// Struct for nodes in the open set of A*
struct OpenNode {
node: Node,
f_score: f32,
}
impl PartialEq for OpenNode {
fn eq(&self, other: &Self) -> bool {
self.f_score >= other.f_score
}
}
impl Eq for OpenNode {}
impl PartialOrd for OpenNode {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
other.f_score.partial_cmp(&self.f_score)
}
}
impl Ord for OpenNode {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other.f_score.cmp(&self.f_score)
}
}
// A* search function
fn astar(graph: &Vec<Node>, start: Node, end: Node) -> Vec<Node> {
let mut open_set = BinaryHeap::new();
let mut came_from = vec![];
open_set.push(OpenNode {
node: start.clone(),
f_score: 0.0
});
while let Some(current) = open_set.pop() {
if current.node.id == end.id {
return reconstruct_path(&came_from, current);
}
for neighbor in current.node.neighbors.iter() {
let new_cost = current.f_score + neighbor.distance as f32;
let new_node = OpenNode {
node: neighbor.clone(),
f_score: new_cost + heuristic(neighbor, end)
};
if !came_from.contains_key(&neighbor.id) {
came_from.insert(neighbor.id, current.node.clone());
open_set.push(new_node);
} else if new_cost < came_from[&neighbor.id].distance as f32 {
came_from.insert(neighbor.id, current.node.clone());
open_set.push(new_node);
}
}
}
vec![]
}
// Heuristic function
fn heuristic(a: &Node, b: Node) -> f32 {
((a.id as f32) - (b.id as f32)).abs()
}
// Reconstruct path from came_from map
fn reconstruct_path(came_from: &Vec<Node>, current: OpenNode) -> Vec<Node> {
let mut path = vec![current.node];
let mut temp = current.node;
while came_from.contains_key(&temp.id) {
temp = came_from[&temp.id].clone();
path.push(temp);
}
path.reverse();
path
}
fn main() {
// Create sample graph
let graph = vec![
Node {
id: 0,
neighbors: vec![Node {id: 1, distance: 5}, Node {id: 2, distance: 3}],
distance: 0
},
Node {
id: 1,
neighbors: vec![Node {id: 0, distance: 5}],
distance: 0
},
Node {
id: 2,
neighbors: vec![Node {id: 0, distance: 3}, Node {id: 3, distance: 1}],
distance: 0
},
Node {
id: 3,
neighbors: vec![Node {id: 2, distance: 1}],
distance: 0
}
];
let start = graph[0].clone();
let end = graph[3].clone();
let path = astar(&graph, start, end);
println!("Cheapest path: {:?}", path);
}