From ab79ffcb60274b89bb04e9dbfe1ec40d185ec920 Mon Sep 17 00:00:00 2001 From: Peter Helbing Date: Sat, 23 Dec 2023 15:26:49 +0100 Subject: [PATCH] Year 2023, Day 23: small optimization --- year2023/src/day23.rs | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/year2023/src/day23.rs b/year2023/src/day23.rs index fde26f6..5d8eb46 100644 --- a/year2023/src/day23.rs +++ b/year2023/src/day23.rs @@ -53,8 +53,8 @@ fn search_longest_path(grid: &Grid2D, icy_path: bool) -> Option { } } - let path = vec![start_pos]; - find_max_path(&distances, 0, path, &end_pos) + let mut path = vec![start_pos]; + find_max_path(&distances, 0, &mut path, &end_pos) } fn find_crossings(grid: &Grid2D) -> HashSet { @@ -74,31 +74,33 @@ fn find_crossings(grid: &Grid2D) -> HashSet { fn find_max_path( distances: &HashMap<(Coords, Coords), usize>, steps: usize, - path: Vec, + path: &mut Vec, end: &Coords, ) -> Option { - let pos = path.last().unwrap(); - if pos == end { + let pos = *path.last().unwrap(); + if &pos == end { return Some(steps); } - let neighbors = distances + let neighbors: Vec<_> = distances .keys() - .filter(|(src, _)| src == pos) - .filter(|(_, dest)| !path.contains(dest)); + .filter(|(src, _)| src == &pos) + .filter(|(_, dest)| !path.contains(dest)) + .to_owned() + .collect(); let mut max_steps = None; for neighbor in neighbors { - let mut new_path = path.clone(); - new_path.push(neighbor.1); + path.push(neighbor.1); let new_steps = steps + distances.get(neighbor).unwrap(); - if let Some(new_steps) = find_max_path(distances, new_steps, new_path, end) { + if let Some(new_steps) = find_max_path(distances, new_steps, path, end) { if let Some(old_steps) = max_steps { max_steps = Some(new_steps.max(old_steps)); } else { max_steps = Some(new_steps); } } + path.pop().unwrap(); } max_steps