Add DijkstraResult return type instead of unnamed tuple

This commit is contained in:
2026-04-22 14:49:07 +02:00
parent 41f2332735
commit a250bde626
2 changed files with 32 additions and 26 deletions
+16 -10
View File
@@ -21,19 +21,25 @@ impl<V: Eq> Ord for DistanceOrderedVertex<V> {
}
}
// TODO: Maybe introduce a return struct type for Dijkstra's algorithm?
pub struct DijkstraResult<V> {
pub distances: Vec<Option<u32>>,
pub predecessors: Vec<Option<V>>,
}
// TODO: Maybe variant of Dijkstra's algorithm without predecessors?
// TODO: Replace Vec storage with VertexMap, this should make the bound on G::Vertex here obsolete.
pub fn dijkstra<G>(graph: &G, source: G::Vertex) -> (Vec<Option<u32>>, Vec<Option<G::Vertex>>)
pub fn dijkstra<G>(graph: &G, source: G::Vertex) -> DijkstraResult<G::Vertex>
where
G: GraphTopology,
G::Vertex: Into<usize>,
{
let mut distances = vec![None; graph.vertex_count()];
let mut predecessors = vec![None; graph.vertex_count()];
let mut result = DijkstraResult {
distances: vec![None; graph.vertex_count()],
predecessors: vec![None; graph.vertex_count()],
};
let mut heap = BinaryHeap::new();
distances[source.into()] = Some(0);
result.distances[source.into()] = Some(0);
heap.push(DistanceOrderedVertex {
vertex: source,
distance: 0,
@@ -43,14 +49,14 @@ where
for neighbor in graph.neighbors(v.vertex) {
// TODO: Add a way to provide custom edge weights for Dijkstra's algorithm.
let edge_weight = 1;
let new_distance = distances[v.vertex.into()].unwrap() + edge_weight;
if match distances[neighbor.into()] {
let new_distance = result.distances[v.vertex.into()].unwrap() + edge_weight;
if match result.distances[neighbor.into()] {
None => true,
Some(old_distance) if old_distance > new_distance => true,
_ => false,
} {
distances[neighbor.into()] = Some(new_distance);
predecessors[neighbor.into()] = Some(v.vertex);
result.distances[neighbor.into()] = Some(new_distance);
result.predecessors[neighbor.into()] = Some(v.vertex);
heap.push(DistanceOrderedVertex {
vertex: neighbor,
distance: new_distance,
@@ -58,5 +64,5 @@ where
}
}
}
(distances, predecessors)
result
}