Skip to content

Commit 70ac675

Browse files
committed
2024: Add Hasher based solution for Day 10
1 parent 141dcd9 commit 70ac675

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

2024/day10/src/main.rs

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
44
use std::{fs, io};
55
use std::collections::{BTreeMap, BTreeSet};
6+
use std::hash::{DefaultHasher, Hash, Hasher};
67
use std::path::Path;
78
use lib::vector::Vector;
89

@@ -73,28 +74,36 @@ fn part2(input: &Input) -> usize {
7374
fn rating(trailhead: Vec2, heights: &BTreeMap<Vec2, u8>) -> usize {
7475
let mut rating = 0;
7576

76-
let mut visited: BTreeSet<Vec<Vec2>> = [vec![trailhead]].into_iter().collect();
77-
let mut edge = vec![vec![trailhead]];
77+
let mut hasher = DefaultHasher::new();
78+
trailhead.hash(&mut hasher);
79+
let hash = hasher.finish();
7880

79-
while let Some(trail) = edge.pop() {
80-
let pos = *trail.last().unwrap();
81+
let mut visited: BTreeSet<u64> = [hash].into_iter().collect();
82+
let mut edge = vec![(trailhead, hasher)];
83+
84+
while let Some((pos, hasher)) = edge.pop() {
8185
let height = heights[&pos];
86+
8287
if height == 9 {
8388
rating += 1;
8489
continue;
8590
}
8691

8792
for dir in [UP, DOWN, LEFT, RIGHT] {
8893
let next_pos = pos + dir;
89-
let new_trail: Vec<_> = trail.iter().copied().chain([next_pos]).collect();
9094

91-
if visited.contains(&new_trail) {
95+
let mut hasher = hasher.clone();
96+
next_pos.hash(&mut hasher);
97+
let hash = hasher.finish();
98+
99+
if visited.contains(&hash) {
92100
continue;
93101
}
94102

103+
visited.insert(hash);
104+
95105
if heights.get(&next_pos).copied() == Some(height + 1) {
96-
visited.insert(new_trail.clone());
97-
edge.push(new_trail);
106+
edge.push((next_pos, hasher));
98107
}
99108
}
100109
}

0 commit comments

Comments
 (0)