1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2026 Dragonscale Team
//! K-Shortest Paths Algorithm (Yen's Algorithm).
//!
//! Finds the K shortest loop-less paths from source to target.
use crate::algo::GraphProjection;
use crate::algo::algorithms::Algorithm;
use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashSet};
use uni_common::core::id::Vid;
pub struct KShortestPaths;
#[derive(Debug, Clone)]
pub struct KShortestPathsConfig {
pub source: Vid,
pub target: Vid,
pub k: usize,
}
impl Default for KShortestPathsConfig {
fn default() -> Self {
Self {
source: Vid::from(0),
target: Vid::from(0),
k: 1,
}
}
}
pub struct KShortestPathsResult {
pub paths: Vec<(Vec<Vid>, f64)>, // (path, cost)
}
impl Algorithm for KShortestPaths {
type Config = KShortestPathsConfig;
type Result = KShortestPathsResult;
fn name() -> &'static str {
"k_shortest_paths"
}
fn run(graph: &GraphProjection, config: Self::Config) -> Self::Result {
let source_slot = match graph.to_slot(config.source) {
Some(s) => s,
None => return KShortestPathsResult { paths: Vec::new() },
};
let target_slot = match graph.to_slot(config.target) {
Some(s) => s,
None => return KShortestPathsResult { paths: Vec::new() },
};
if config.k == 0 {
return KShortestPathsResult { paths: Vec::new() };
}
let mut a: Vec<(Vec<u32>, f64)> = Vec::new();
// 1. First shortest path
let (path0, cost0) = match run_dijkstra(graph, source_slot, target_slot, &HashSet::new()) {
Some(res) => res,
None => return KShortestPathsResult { paths: Vec::new() },
};
a.push((path0, cost0));
let mut b: BinaryHeap<Reverse<(u64, Vec<u32>)>> = BinaryHeap::new();
// 2. Iterate for k
for k in 1..config.k {
let prev_path = &a[k - 1].0;
// The spur node ranges from the first node to the next-to-last node in the previous k-shortest path.
for i in 0..prev_path.len() - 1 {
let spur_node = prev_path[i];
let root_path = &prev_path[0..=i];
let root_path_cost = calculate_path_cost(graph, root_path);
let mut forbidden_edges = HashSet::new();
for (p_path, _) in &a {
if p_path.len() > i && &p_path[0..=i] == root_path {
forbidden_edges.insert((p_path[i], p_path[i + 1]));
}
}
// Remove root path nodes from graph (except spur node) to ensure loopless
// We simulate this by checking if neighbor is in root_path (excluding spur)
// Actually Yen's usually ensures loopless.
// Standard implementation: disable nodes in root path.
// Run Dijkstra from spur node to target
if let Some((spur_path, spur_cost)) = run_dijkstra_with_constraints(
graph,
spur_node,
target_slot,
&forbidden_edges,
root_path, // forbidden nodes are root_path[0..i] (excluding spur which is root_path[i])
) {
let mut total_path = root_path[0..i].to_vec();
total_path.extend(spur_path);
let total_cost = root_path_cost + spur_cost; // root_path excludes last edge to spur? No, root_path includes spur.
// Wait, root_path includes spur. path cost calculation logic needs to be precise.
// Logic check:
// root_path = [s, ..., spur]
// spur_path = [spur, ..., t]
// total = [s, ..., spur, ..., t]
// cost = cost(s..spur) + cost(spur..t)
// Using bits for f64 ordering in heap
let entry = Reverse((total_cost.to_bits(), total_path));
// Ideally verify uniqueness before pushing to heap, but B handles sorting.
// Duplicate paths might be generated.
// We should check if path is already in B?
// BinaryHeap doesn't support contains.
// Typically B is a set or we push and then dedup when popping.
// Optimization: check if already in B? Too slow.
// Just push.
b.push(entry);
}
}
if b.is_empty() {
break;
}
// Extract best from B
// Need to handle duplicates
let mut best_path = None;
while let Some(Reverse((cost_bits, path))) = b.pop() {
let cost = f64::from_bits(cost_bits);
// Check if path is already in A
let exists = a.iter().any(|(p, _)| p == &path);
if !exists {
best_path = Some((path, cost));
break;
}
}
if let Some(bp) = best_path {
a.push(bp);
} else {
break;
}
}
let mapped_paths = a
.into_iter()
.map(|(path, cost)| {
let vids = path.iter().map(|&slot| graph.to_vid(slot)).collect();
(vids, cost)
})
.collect();
KShortestPathsResult {
paths: mapped_paths,
}
}
}
fn calculate_path_cost(graph: &GraphProjection, path: &[u32]) -> f64 {
let mut cost = 0.0;
for i in 0..path.len() - 1 {
let u = path[i];
let v = path[i + 1];
// Find edge weight
// Linear scan of neighbors
let neighbors = graph.out_neighbors(u);
let mut weight = 1.0;
if graph.has_weights() {
for (idx, &n) in neighbors.iter().enumerate() {
if n == v {
weight = graph.out_weight(u, idx);
break;
}
}
}
cost += weight;
}
cost
}
fn run_dijkstra(
graph: &GraphProjection,
source: u32,
target: u32,
forbidden_edges: &HashSet<(u32, u32)>,
) -> Option<(Vec<u32>, f64)> {
run_dijkstra_with_constraints(graph, source, target, forbidden_edges, &[])
}
fn run_dijkstra_with_constraints(
graph: &GraphProjection,
source: u32,
target: u32,
forbidden_edges: &HashSet<(u32, u32)>,
forbidden_nodes: &[u32],
) -> Option<(Vec<u32>, f64)> {
let n = graph.vertex_count();
let mut dist = vec![f64::INFINITY; n];
let mut prev = vec![None; n];
let mut heap = BinaryHeap::new();
dist[source as usize] = 0.0;
heap.push(Reverse((0.0f64.to_bits(), source)));
let forbidden_nodes_set: HashSet<u32> = forbidden_nodes.iter().cloned().collect();
while let Some(Reverse((d_bits, u))) = heap.pop() {
let d = f64::from_bits(d_bits);
if d > dist[u as usize] {
continue;
}
if u == target {
break;
}
for (i, &v) in graph.out_neighbors(u).iter().enumerate() {
if forbidden_nodes_set.contains(&v) {
continue;
}
if forbidden_edges.contains(&(u, v)) {
continue;
}
let weight = if graph.has_weights() {
graph.out_weight(u, i)
} else {
1.0
};
let new_dist = d + weight;
if new_dist < dist[v as usize] {
dist[v as usize] = new_dist;
prev[v as usize] = Some(u);
heap.push(Reverse((new_dist.to_bits(), v)));
}
}
}
if dist[target as usize] == f64::INFINITY {
return None;
}
let mut path = Vec::new();
let mut curr = Some(target);
while let Some(slot) = curr {
path.push(slot);
if slot == source {
break;
}
curr = prev[slot as usize];
}
path.reverse();
Some((path, dist[target as usize]))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::algo::test_utils::build_test_graph;
#[test]
fn test_ksp_simple() {
// 0 -> 1 -> 3 (cost 2)
// 0 -> 2 -> 3 (cost 2)
// 0 -> 3 (cost 10 - not possible in unit weight without custom builder)
// Let's rely on hop count as cost (1.0).
// 0->1->3 (2.0)
// 0->2->3 (2.0)
let vids = vec![Vid::from(0), Vid::from(1), Vid::from(2), Vid::from(3)];
let edges = vec![
(Vid::from(0), Vid::from(1)),
(Vid::from(1), Vid::from(3)),
(Vid::from(0), Vid::from(2)),
(Vid::from(2), Vid::from(3)),
];
let graph = build_test_graph(vids, edges);
let config = KShortestPathsConfig {
source: Vid::from(0),
target: Vid::from(3),
k: 2,
};
let result = KShortestPaths::run(&graph, config);
assert_eq!(result.paths.len(), 2);
assert_eq!(result.paths[0].1, 2.0);
assert_eq!(result.paths[1].1, 2.0);
}
}