Add GraphTopology trait and use it to interface graph model with algorithm
This commit is contained in:
+18
-13
@@ -1,22 +1,21 @@
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::BinaryHeap;
|
||||
|
||||
use crate::models::Graph;
|
||||
use crate::models::Vertex;
|
||||
use crate::traits::GraphTopology;
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct DistanceOrderedVertex {
|
||||
struct DistanceOrderedVertex<V> {
|
||||
distance: u32,
|
||||
vertex: Vertex,
|
||||
vertex: V,
|
||||
}
|
||||
|
||||
impl PartialOrd for DistanceOrderedVertex {
|
||||
impl<V: Eq> PartialOrd for DistanceOrderedVertex<V> {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.distance.cmp(&other.distance))
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for DistanceOrderedVertex {
|
||||
impl<V: Eq> Ord for DistanceOrderedVertex<V> {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
other.distance.cmp(&self.distance)
|
||||
}
|
||||
@@ -24,28 +23,34 @@ impl Ord for DistanceOrderedVertex {
|
||||
|
||||
// TODO: Maybe introduce a return struct type for Dijkstra's algorithm?
|
||||
// TODO: Maybe variant of Dijkstra's algorithm without predecessors?
|
||||
pub fn dijkstra(graph: &Graph, source: Vertex) -> (Vec<Option<u32>>, Vec<Option<Vertex>>) {
|
||||
// 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>>)
|
||||
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 heap = BinaryHeap::new();
|
||||
|
||||
distances[source.0] = Some(0);
|
||||
distances[source.into()] = Some(0);
|
||||
heap.push(DistanceOrderedVertex {
|
||||
vertex: source,
|
||||
distance: 0,
|
||||
});
|
||||
|
||||
while let Some(v) = heap.pop() {
|
||||
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.0].unwrap() + edge_weight;
|
||||
if match distances[neighbor.0] {
|
||||
let new_distance = distances[v.vertex.into()].unwrap() + edge_weight;
|
||||
if match distances[neighbor.into()] {
|
||||
None => true,
|
||||
Some(old_distance) if old_distance > new_distance => true,
|
||||
_ => false,
|
||||
} {
|
||||
distances[neighbor.0] = Some(new_distance);
|
||||
predecessors[neighbor.0] = Some(v.vertex);
|
||||
distances[neighbor.into()] = Some(new_distance);
|
||||
predecessors[neighbor.into()] = Some(v.vertex);
|
||||
heap.push(DistanceOrderedVertex {
|
||||
vertex: neighbor,
|
||||
distance: new_distance,
|
||||
|
||||
Reference in New Issue
Block a user