From 09d6b5e3e1a22532ed2e2cb8cbf6e6f12d50e72e Mon Sep 17 00:00:00 2001 From: Kevin Caffrey Date: Sat, 23 Dec 2023 16:49:57 -0500 Subject: [PATCH] iterative is always faster than recursive --- README.md | 4 ++-- src/bin/23.rs | 40 +++++++++++++--------------------------- 2 files changed, 15 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 66b8dfa..b04ca12 100644 --- a/README.md +++ b/README.md @@ -61,9 +61,9 @@ Solutions for [Advent of Code](https://adventofcode.com/) in [Rust](https://www. | [Day 20](./src/bin/20.rs) | `323.9µs` | `1.2ms` | | [Day 21](./src/bin/21.rs) | `64.1µs` | `494.7µs` | | [Day 22](./src/bin/22.rs) | `78.3µs` | `194.8µs` | -| [Day 23](./src/bin/23.rs) | `330.7µs` | `67.4ms` | +| [Day 23](./src/bin/23.rs) | `330.4µs` | `23.9ms` | -**Total: 84.34ms** +**Total: 40.84ms** --- diff --git a/src/bin/23.rs b/src/bin/23.rs index a518c81..f155524 100644 --- a/src/bin/23.rs +++ b/src/bin/23.rs @@ -46,36 +46,22 @@ pub fn part_two(input: &str) -> Option { goal = new_goal; } - Some(trimmed_length + part_two_recursive_brute_force(&graph, start, goal, 1 << start, 0)) -} - -fn part_two_recursive_brute_force( - graph: &Graph, - cur: usize, - goal: usize, - visited: u64, - so_far: u16, -) -> u16 { - if cur == goal { - return so_far; - } - - let mut max = 0; - for &(neighbor, cost) in &graph.adjacency[cur] { - let neighbor_bit = 1 << neighbor; - if (visited & neighbor_bit) == 0 { - let next_so_far = part_two_recursive_brute_force( - graph, - neighbor, - goal, - visited | neighbor_bit, - so_far + cost, - ); - max = max.max(next_so_far); + // Now do a simple exhaustive DFS search to find the longest path + // to the goal (and add in the amount we trimmed). + let mut stack = Vec::new(); + stack.push((start, 1 << start, 0)); + let mut best = 0; + while let Some((cur, visited, so_far)) = stack.pop() { + for &(neighbor, cost) in &graph.adjacency[cur] { + if neighbor == goal { + best = best.max(so_far + cost); + } else if visited & (1 << neighbor) == 0 { + stack.push((neighbor, visited | (1 << neighbor), so_far + cost)); + } } } - max + Some(trimmed_length + best) } fn build_graph(input: &str, obey_slopes: bool) -> (Graph, usize, usize) {