Advertisement
theultraman20

dijkstra.rs

Sep 9th, 2024
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.65 KB | None | 0 0
  1. use crate::graph::*;
  2. use crate::hash_map::HashMap;
  3. use crate::q::PriorityQ;
  4. use std::hash::Hash;
  5.  
  6. //Not sure if I spelled this right lol
  7. pub fn dijkstra<T: Hash + Eq + PartialOrd + GraphNode<T>>(start: &T, goal: &T) {
  8.     let mut pq = PriorityQ::<&T>::new();
  9.     //HashMap<Elem, (prev nghbr with least dist, dist from prev nghbr)>
  10.     //consider using struct to improve readability
  11.     let mut node_meta = HashMap::<&T, (Option<&T>, usize)>::new();
  12.     //visited means all of it's neighbors have been queued, not whether or not
  13.     //it's distance values have been added
  14.     //using a hashmap with unit type because I didn't feel like implementing hash set too lmao
  15.     let mut visited = HashMap::<&T, ()>::new();
  16.     pq.push(start, 0);
  17.     node_meta.insert(start, (None, 0));
  18.  
  19.     while !pq.is_empty() {
  20.         let (curr_elem, cum_dist) = pq.pop().unwrap();
  21.         visited.insert(curr_elem, ());
  22.         if curr_elem == goal {
  23.             break;
  24.         }
  25.  
  26.         for (neighbor, nghbr_dist) in curr_elem.get_neighbors() {
  27.             //note: possible optimization would be caching hash or giving a hash hint
  28.             //since we're hashing the same element twice
  29.             //is_none_or is available with nightly rust, but I don't think it's worth the switch
  30.             if node_meta.get(&neighbor).is_none()
  31.                 || cum_dist + nghbr_dist < node_meta.get(&neighbor).unwrap().1
  32.             {
  33.                 node_meta.insert(neighbor, (Some(curr_elem), cum_dist + nghbr_dist));
  34.             }
  35.  
  36.             if visited.get(&neighbor).is_none() {
  37.                 pq.push(&neighbor, cum_dist + nghbr_dist);
  38.             }
  39.         }
  40.     }
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement