Skip to content

Commit

Permalink
iterative is always faster than recursive
Browse files Browse the repository at this point in the history
  • Loading branch information
kcaffrey committed Dec 23, 2023
1 parent 596d63e commit 09d6b5e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 29 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
<!--- benchmarking table --->

---
Expand Down
40 changes: 13 additions & 27 deletions src/bin/23.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,36 +46,22 @@ pub fn part_two(input: &str) -> Option<u16> {
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) {
Expand Down

0 comments on commit 09d6b5e

Please sign in to comment.