Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
fix: floyd warshall d[i][i] == 0 case (TheAlgorithms#428)
  • Loading branch information
wingkwong authored Jan 22, 2023
commit f69c5123abbdf53ac56a8630016bd4d00d9f1cf8
17 changes: 14 additions & 3 deletions src/graph/floyd_warshall.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use num_traits::Zero;
use std::collections::BTreeMap;
use std::ops::Add;

Expand All @@ -13,18 +14,20 @@ type Graph<V, E> = BTreeMap<V, BTreeMap<V, E>>;
///
/// For a key v, if map[v].len() == 0, then v cannot reach any other vertex, but is in the graph
/// (island node, or sink in the case of a directed graph)
pub fn floyd_warshall<V: Ord + Copy, E: Ord + Copy + Add<Output = E>>(
pub fn floyd_warshall<V: Ord + Copy, E: Ord + Copy + Add<Output = E> + num_traits::Zero>(
graph: &Graph<V, E>,
) -> BTreeMap<V, BTreeMap<V, E>> {
let mut map: BTreeMap<V, BTreeMap<V, E>> = BTreeMap::new();
for (u, edges) in graph.iter() {
if !map.contains_key(u) {
map.insert(*u, BTreeMap::new());
}
map.entry(*u).or_default().insert(*u, Zero::zero());
for (v, weight) in edges.iter() {
if !map.contains_key(v) {
map.insert(*v, BTreeMap::new());
}
map.entry(*v).or_default().insert(*v, Zero::zero());
map.entry(*u).and_modify(|mp| {
mp.insert(*v, *weight);
});
Expand Down Expand Up @@ -83,7 +86,7 @@ mod tests {

let mut dists = BTreeMap::new();
dists.insert(0, BTreeMap::new());

dists.get_mut(&0).unwrap().insert(0, 0);
assert_eq!(floyd_warshall(&graph), dists);
}

Expand All @@ -94,9 +97,12 @@ mod tests {
bi_add_edge(&mut graph, 1, 2, 3);

let mut dists_0 = BTreeMap::new();
dists_0.insert(0, BTreeMap::new());
dists_0.insert(1, BTreeMap::new());
dists_0.insert(2, BTreeMap::new());
dists_0.insert(0, BTreeMap::new());
dists_0.get_mut(&0).unwrap().insert(0, 0);
dists_0.get_mut(&1).unwrap().insert(1, 0);
dists_0.get_mut(&2).unwrap().insert(2, 0);
dists_0.get_mut(&1).unwrap().insert(0, 2);
dists_0.get_mut(&0).unwrap().insert(1, 2);
dists_0.get_mut(&1).unwrap().insert(2, 3);
Expand All @@ -120,6 +126,11 @@ mod tests {
let mut dists_a = BTreeMap::new();
dists_a.insert('d', BTreeMap::new());

dists_a.entry('a').or_insert(BTreeMap::new()).insert('a', 0);
dists_a.entry('b').or_insert(BTreeMap::new()).insert('b', 0);
dists_a.entry('c').or_insert(BTreeMap::new()).insert('c', 0);
dists_a.entry('d').or_insert(BTreeMap::new()).insert('d', 0);
dists_a.entry('e').or_insert(BTreeMap::new()).insert('e', 0);
dists_a
.entry('a')
.or_insert(BTreeMap::new())
Expand Down