1use crate::graph::Graph;
6use lib_jsl_core::ErrorsJSL;
7use std::cmp::Ordering;
8use std::collections::BinaryHeap;
9
10#[derive(Debug, Clone, PartialEq)]
12pub struct ShortestPaths {
13 pub source: usize,
14 pub distance: Vec<f64>,
16 pub predecessor: Vec<Option<usize>>,
18}
19
20impl ShortestPaths {
21 pub fn path_to(&self, target: usize) -> Option<Vec<usize>> {
23 if !self.distance[target].is_finite() {
24 return None;
25 }
26 let mut path = vec![target];
27 let mut v = target;
28 while let Some(p) = self.predecessor[v] {
29 path.push(p);
30 v = p;
31 }
32 path.reverse();
33 Some(path)
34 }
35}
36
37#[derive(PartialEq)]
39struct State {
40 cost: f64,
41 vertex: usize,
42}
43impl Eq for State {}
44impl PartialOrd for State {
45 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
46 Some(self.cmp(other))
47 }
48}
49impl Ord for State {
50 fn cmp(&self, other: &Self) -> Ordering {
51 other.cost.total_cmp(&self.cost)
52 }
53}
54
55fn check_source(g: &Graph, source: usize) -> Result<(), ErrorsJSL> {
56 if source >= g.vertex_count() {
57 return Err(ErrorsJSL::InvalidInputRange("The source vertex is out of range."));
58 }
59 Ok(())
60}
61
62pub fn dijkstra(g: &Graph, source: usize) -> Result<ShortestPaths, ErrorsJSL> {
65 check_source(g, source)?;
66 if g.edges().iter().any(|e| e.weight < 0.0 || e.weight.is_nan()) {
67 return Err(ErrorsJSL::InvalidInputRange("Dijkstra's algorithm needs non-negative weights; use Bellman-Ford."));
68 }
69 let n = g.vertex_count();
70 let mut distance = vec![f64::INFINITY; n];
71 let mut predecessor = vec![None; n];
72 distance[source] = 0.0;
73 let mut heap = BinaryHeap::from([State { cost: 0.0, vertex: source }]);
74 while let Some(State { cost, vertex }) = heap.pop() {
76 if cost > distance[vertex] {
77 continue;
78 }
79 for &(next, w) in g.neighbors(vertex) {
80 let candidate = cost + w;
81 if candidate < distance[next] {
82 distance[next] = candidate;
83 predecessor[next] = Some(vertex);
84 heap.push(State { cost: candidate, vertex: next });
85 }
86 }
87 }
88 Ok(ShortestPaths { source, distance, predecessor })
90}
91
92pub fn bellman_ford(g: &Graph, source: usize) -> Result<ShortestPaths, ErrorsJSL> {
95 check_source(g, source)?;
96 let n = g.vertex_count();
97 let edges = g.edges();
98 let both_ways = !g.is_directed();
99 let mut distance = vec![f64::INFINITY; n];
100 let mut predecessor = vec![None; n];
101 distance[source] = 0.0;
102 let relax = |distance: &mut Vec<f64>, predecessor: &mut Vec<Option<usize>>| {
103 let mut changed = false;
104 for e in &edges {
105 for (u, v) in if both_ways { vec![(e.from, e.to), (e.to, e.from)] } else { vec![(e.from, e.to)] } {
106 if distance[u].is_finite() && distance[u] + e.weight < distance[v] {
107 distance[v] = distance[u] + e.weight;
108 predecessor[v] = Some(u);
109 changed = true;
110 }
111 }
112 }
113 changed
114 };
115 for _ in 1..n {
116 if !relax(&mut distance, &mut predecessor) {
117 return Ok(ShortestPaths { source, distance, predecessor });
118 }
119 }
120 if relax(&mut distance, &mut predecessor) {
121 return Err(ErrorsJSL::RuntimeError("A negative cycle is reachable from the source."));
122 }
123 Ok(ShortestPaths { source, distance, predecessor })
124}
125
126pub fn a_star<H: Fn(usize) -> f64>(g: &Graph, source: usize, target: usize, heuristic: H) -> Result<Option<(f64, Vec<usize>)>, ErrorsJSL> {
131 check_source(g, source)?;
132 check_source(g, target)?;
133 let n = g.vertex_count();
134 let mut cost = vec![f64::INFINITY; n];
135 let mut predecessor = vec![None; n];
136 let mut closed = vec![false; n];
137 cost[source] = 0.0;
138 let mut heap = BinaryHeap::from([State { cost: heuristic(source), vertex: source }]);
139 while let Some(State { vertex, .. }) = heap.pop() {
140 if vertex == target {
141 let paths = ShortestPaths { source, distance: cost.clone(), predecessor };
142 return Ok(Some((cost[target], paths.path_to(target).expect("reached"))));
143 }
144 if closed[vertex] {
145 continue;
146 }
147 closed[vertex] = true;
148 for &(next, w) in g.neighbors(vertex) {
149 if w < 0.0 {
150 return Err(ErrorsJSL::InvalidInputRange("A* needs non-negative weights."));
151 }
152 let candidate = cost[vertex] + w;
153 if candidate < cost[next] {
154 cost[next] = candidate;
155 predecessor[next] = Some(vertex);
156 heap.push(State { cost: candidate + heuristic(next), vertex: next });
157 }
158 }
159 }
160 Ok(None)
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166
167 fn classic() -> Graph {
168 Graph::from_edges(6, &[(0, 1, 7.0), (0, 2, 9.0), (0, 5, 14.0), (1, 2, 10.0), (1, 3, 15.0), (2, 3, 11.0), (2, 5, 2.0), (3, 4, 6.0), (4, 5, 9.0)], false).unwrap()
170 }
171
172 #[test]
173 fn dijkstra_and_bellman_ford_agree() {
174 let g = classic();
175 let d = dijkstra(&g, 0).unwrap();
176 assert_eq!(d.distance, vec![0.0, 7.0, 9.0, 20.0, 20.0, 11.0]);
177 assert_eq!(d.path_to(4).unwrap(), vec![0, 2, 5, 4]);
178 assert_eq!(bellman_ford(&g, 0).unwrap().distance, d.distance);
179 let disconnected = Graph::from_edges(3, &[(0, 1, 1.0)], true).unwrap();
180 let s = dijkstra(&disconnected, 0).unwrap();
181 assert!(s.distance[2].is_infinite() && s.path_to(2).is_none());
182 assert!(dijkstra(&Graph::from_edges(2, &[(0, 1, -1.0)], true).unwrap(), 0).is_err());
183 }
184
185 #[test]
186 fn bellman_ford_handles_negative_edges_and_detects_negative_cycles() {
187 let g = Graph::from_edges(5, &[(0, 1, 6.0), (0, 3, 7.0), (1, 2, 5.0), (1, 3, 8.0), (1, 4, -4.0), (2, 1, -2.0), (3, 2, -3.0), (3, 4, 9.0), (4, 0, 2.0), (4, 2, 7.0)], true).unwrap();
188 let s = bellman_ford(&g, 0).unwrap();
189 assert_eq!(s.distance, vec![0.0, 2.0, 4.0, 7.0, -2.0]);
190 assert_eq!(s.path_to(4).unwrap(), vec![0, 3, 2, 1, 4]);
191 let cycle = Graph::from_edges(3, &[(0, 1, 1.0), (1, 2, -2.0), (2, 1, 1.0)], true).unwrap();
192 assert!(bellman_ford(&cycle, 0).is_err());
193 }
194
195 #[test]
196 fn a_star_on_a_grid_expands_optimally() {
197 let w = 20;
199 let id = |x: usize, y: usize| y * w + x;
200 let wall = |x: usize, y: usize| x == 10 && y < 15;
201 let mut edges = Vec::new();
202 for y in 0..w {
203 for x in 0..w {
204 if wall(x, y) {
205 continue;
206 }
207 if x + 1 < w && !wall(x + 1, y) {
208 edges.push((id(x, y), id(x + 1, y), 1.0));
209 }
210 if y + 1 < w && !wall(x, y + 1) {
211 edges.push((id(x, y), id(x, y + 1), 1.0));
212 }
213 }
214 }
215 let g = Graph::from_edges(w * w, &edges, false).unwrap();
216 let goal = id(19, 0);
217 let manhattan = |v: usize| ((v % w).abs_diff(19) + (v / w)) as f64;
218 let (cost, path) = a_star(&g, id(0, 0), goal, manhattan).unwrap().unwrap();
219 assert_eq!(cost, dijkstra(&g, id(0, 0)).unwrap().distance[goal]);
220 assert_eq!(cost, 19.0 + 2.0 * 15.0);
221 assert_eq!(path.len(), cost as usize + 1);
222 assert!(a_star(&g, id(10, 0), goal, manhattan).unwrap().is_none()); }
224}