Certainly! Here's an example of a Rust program that uses the A* algorithm to find the cheapest path between two nodes in a graph:
use std::collections::{BinaryHeap, HashMap};
use std::cmp::Ordering;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct Node {
id: usize,
cost: u32,
}
impl Node {
fn new(id: usize, cost: u32) -> Node {
Node { id, cost }
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct Edge {
target: usize,
cost: u32,
}
struct Graph {
edges: Vec<Vec<Edge>>,
}
impl Graph {
fn new(num_nodes: usize) -> Graph {
Graph {
edges: vec![Vec::new(); num_nodes],
}
}
fn add_edge(&mut self, source: usize, target: usize, cost: u32) {
self.edges[source].push(Edge { target, cost });
}
fn a_star(&self, start: usize, goal: usize) -> Option<Vec<usize>> {
let mut open_set: BinaryHeap<Node> = BinaryHeap::new();
let mut came_from: HashMap<usize, usize> = HashMap::new();
let mut g_score: HashMap<usize, u32> = HashMap::new();
let mut f_score: HashMap<usize, u32> = HashMap::new();
g_score.insert(start, 0);
f_score.insert(start, self.heuristic(start, goal));
open_set.push(Node::new(start, f_score[&start]));
while let Some(current) = open_set.pop() {
if current.id == goal {
return Some(Self::reconstruct_path(&came_from, goal));
}
for edge in &self.edges[current.id] {
let neighbor = edge.target;
let tentative_g_score = g_score[¤t.id] + edge.cost;
if !g_score.contains_key(&neighbor) || tentative_g_score < g_score[&neighbor] {
came_from.insert(neighbor, current.id);
g_score.insert(neighbor, tentative_g_score);
f_score.insert(neighbor, tentative_g_score + self.heuristic(neighbor, goal));
open_set.push(Node::new(neighbor, f_score[&neighbor]));
}
}
}
None
}
fn heuristic(&self, node: usize, goal: usize) -> u32 {
// Example heuristic: Euclidean distance
let x1 = (node % 10) as i32;
let y1 = (node / 10) as i32;
let x2 = (goal % 10) as i32;
let y2 = (goal / 10) as i32;
(((x1 - x2).pow(2) + (y1 - y2).pow(2)) as f64).sqrt() as u32
}
fn reconstruct_path(came_from: &HashMap<usize, usize>, current: usize) -> Vec<usize> {
let mut path = Vec::new();
path.push(current);
let mut node = current;
while let Some(&prev) = came_from.get(&node) {
path.push(prev);
node = prev;
}
path.reverse();
path
}
}
fn main() {
let mut graph = Graph::new(100);
// Example graph
for i in 0..10 {
for j in 0..10 {
let current = i * 10 + j;
if j < 9 {
graph.add_edge(current, current + 1, 1);
}
if i < 9 {
graph.add_edge(current, current + 10, 1);
}
}
}
let start = 0;
let goal = 99;
if let Some(path) = graph.a_star(start, goal) {
println!("Cheapest path: {:?}", path);
} else {
println!("No path found.");
}
}