|
| 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