Skip to content

Commit 93a7b22

Browse files
authored
add dijkstra's algorithm in rust (#294)
1 parent 741c11b commit 93a7b22

File tree

3 files changed

+83
-0
lines changed

3 files changed

+83
-0
lines changed

09_dijkstras_algorithm/rust/Cargo.lock

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[package]
2+
name = "dijkstra"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
use std::{collections::HashMap, u64};
2+
3+
fn find_lowest_cost_node(processed: &Vec<String>, costs: &HashMap<String, u64>) -> Option<String> {
4+
let mut lowest_cost = u64::MAX;
5+
let mut lowest_cost_node = None;
6+
for (node, cost) in costs.iter() {
7+
if *cost < lowest_cost && !processed.contains(node) {
8+
lowest_cost = *cost;
9+
lowest_cost_node = Some(node);
10+
}
11+
}
12+
return lowest_cost_node.cloned();
13+
}
14+
15+
fn main() {
16+
// Graph Setup
17+
let mut graph = HashMap::new();
18+
19+
let mut start_edges: HashMap<String, u64> = HashMap::new();
20+
start_edges.insert("a".to_string(), 6);
21+
start_edges.insert("b".to_string(), 2);
22+
graph.insert("start".to_string(), start_edges);
23+
24+
let mut a_edges = HashMap::new();
25+
a_edges.insert("fin".to_string(), 1);
26+
graph.insert("a".to_string(), a_edges);
27+
28+
let mut b_edges = HashMap::new();
29+
b_edges.insert("a".to_string(), 3);
30+
b_edges.insert("fin".to_string(), 5);
31+
graph.insert("b".to_string(), b_edges);
32+
33+
let fin_edges = HashMap::new();
34+
graph.insert("fin".to_string(), fin_edges);
35+
36+
// Costs Setup
37+
let mut costs: HashMap<String, u64> = HashMap::new();
38+
costs.insert("a".to_string(), 6);
39+
costs.insert("b".to_string(), 2);
40+
costs.insert("fin".to_string(), u64::MAX);
41+
42+
// Parents Setup
43+
let mut parents = HashMap::new();
44+
parents.insert("a".to_string(), Some("start".to_string()));
45+
parents.insert("b".to_string(), Some("start".to_string()));
46+
parents.insert("fin".to_string(), None);
47+
48+
let mut processed: Vec<String> = vec![];
49+
50+
loop {
51+
let node = find_lowest_cost_node(&processed, &costs);
52+
match node {
53+
Some(node) => {
54+
let cost = *costs.get(&node).unwrap();
55+
let neighbors = graph.get(&node).unwrap();
56+
for (n, ncost) in neighbors.iter() {
57+
let new_cost = cost + *ncost;
58+
if *costs.get(n).unwrap() > new_cost {
59+
costs.insert(n.to_string(), new_cost);
60+
parents.insert(n.to_string(), Some(node.clone()));
61+
}
62+
}
63+
processed.push(node)
64+
}
65+
None => break,
66+
}
67+
}
68+
println!("costs: {:?}", costs);
69+
println!("parents: {:?}", parents);
70+
}

0 commit comments

Comments
 (0)