From 4a407de45bc4afd9682b7d22e789f9eea79ae018 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Wed, 15 Dec 2021 13:56:18 -0500 Subject: [PATCH] Use BinaryHeap for day15 dijkstra --- Cargo.toml | 3 +++ src/day15.rs | 37 +++++++++++++++++-------------------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 471ab37..49c8df8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,3 +8,6 @@ edition = "2021" [dependencies] itertools = "0.10.3" ansi_term = "0.12.1" + +[profile.release] +debug = true diff --git a/src/day15.rs b/src/day15.rs index 3c4e814..508fdab 100644 --- a/src/day15.rs +++ b/src/day15.rs @@ -1,4 +1,4 @@ -use std::collections::{HashMap, HashSet}; +use std::collections::BinaryHeap; pub fn day15() { // let input = r#" @@ -21,7 +21,7 @@ pub fn day15() { let graph: Graph<100> = input.into(); let path = dijkstra(&graph, graph.size(), &(0, 0), &graph.bottom_right()); - println!("found path: {:?}", path); + // println!("found path: {:?}", path); println!("path risk: {}", path_risk(&graph, &path.unwrap())); let path = dijkstra( @@ -30,7 +30,7 @@ pub fn day15() { &(0, 0), &(graph.size() * 5 - 1, graph.size() * 5 - 1), ); - println!("{:?}", path); + // println!("{:?}", path); println!("path risk: {}", path_risk(&graph, &path.unwrap())); } @@ -88,21 +88,15 @@ fn dijkstra( source: &Point, target: &Point, ) -> Option> { - let mut q: HashSet = HashSet::new(); - let mut dist = vec![vec![0; size]; size]; + let mut q: BinaryHeap<(isize, Point)> = BinaryHeap::new(); + let mut dist = vec![vec![usize::MAX; size]; size]; let mut prev = vec![vec![None; size]; size]; - for x in 0..size { - for y in 0..size { - dist[x][y] = usize::max_value(); - q.insert((x, y)); - } - } dist[source.0][source.1] = 0; + q.push((0, *source)); - while let Some(u) = q.iter().min_by_key(|p| dist[p.0][p.1]) { - let u = u.clone(); - q.remove(&u); + while let Some((neg_cost, u)) = q.pop() { + let cost = -neg_cost as usize; if u == *target { let mut s = vec![]; @@ -114,13 +108,16 @@ fn dijkstra( return Some(s); } + if cost > dist[u.0][u.1] { + continue; + } + for v in neighbors(u, size) { - if q.contains(&v) { - let alt = dist[u.0][u.1] + g.risk(&v); - if alt < dist[v.0][v.1] { - dist[v.0][v.1] = alt; - prev[v.0][v.1] = Some(u); - } + let alt = dist[u.0][u.1] + g.risk(&v); + if alt < dist[v.0][v.1] { + dist[v.0][v.1] = alt; + prev[v.0][v.1] = Some(u); + q.push((-(alt as isize), v)); } } }