advanced_algorithms/graph/
mod.rs

1//! Graph algorithms
2//!
3//! This module provides implementations of classic graph algorithms:
4//! - Dijkstra's Algorithm (shortest path)
5//! - A* Search Algorithm (heuristic pathfinding)
6//! - Bellman-Ford Algorithm (shortest path with negative weights)
7//! - Floyd-Warshall Algorithm (all-pairs shortest path)
8
9pub mod dijkstra;
10pub mod astar;
11pub mod bellman_ford;
12pub mod floyd_warshall;
13
14use std::collections::HashMap;
15
16/// Represents a weighted, directed graph
17#[derive(Debug, Clone)]
18pub struct Graph {
19    /// Adjacency list: node -> [(neighbor, weight), ...]
20    pub edges: HashMap<usize, Vec<(usize, f64)>>,
21    /// Number of nodes
22    pub n_nodes: usize,
23}
24
25impl Graph {
26    /// Creates a new empty graph
27    pub fn new(n_nodes: usize) -> Self {
28        Graph {
29            edges: HashMap::new(),
30            n_nodes,
31        }
32    }
33    
34    /// Adds a directed edge from u to v with the given weight
35    pub fn add_edge(&mut self, u: usize, v: usize, weight: f64) {
36        self.edges.entry(u).or_default().push((v, weight));
37    }
38    
39    /// Adds an undirected edge (adds both directions)
40    pub fn add_undirected_edge(&mut self, u: usize, v: usize, weight: f64) {
41        self.add_edge(u, v, weight);
42        self.add_edge(v, u, weight);
43    }
44    
45    /// Returns neighbors of node u
46    pub fn neighbors(&self, u: usize) -> &[(usize, f64)] {
47        self.edges.get(&u).map(|v| v.as_slice()).unwrap_or(&[])
48    }
49}