Day 10 part 2

This commit is contained in:
Daniel Flanagan 2024-12-10 09:43:02 -06:00
parent b17ad64e2f
commit 3bd6fc2600

View file

@ -17,7 +17,7 @@ fn part1(input: &str) -> usize {
for (x, height) in row.iter().enumerate() { for (x, height) in row.iter().enumerate() {
let mut scores = HashSet::new(); let mut scores = HashSet::new();
if *height == 0 { if *height == 0 {
find_paths_to_nines(&map, *height, x, y, &mut scores); capture_scores(&map, *height, x, y, &mut scores);
sum += scores.len(); sum += scores.len();
} }
println!("{x} {y} {height}"); println!("{x} {y} {height}");
@ -26,7 +26,7 @@ fn part1(input: &str) -> usize {
sum sum
} }
fn find_paths_to_nines( fn capture_scores(
map: &Vec<Vec<u8>>, map: &Vec<Vec<u8>>,
height: u8, height: u8,
x: usize, x: usize,
@ -49,13 +49,50 @@ fn find_paths_to_nines(
let next_height = map[ny][nx]; let next_height = map[ny][nx];
if next_height.saturating_sub(height) == 1 { if next_height.saturating_sub(height) == 1 {
println!("{height} -> {next_height} at {nx},{ny}"); println!("{height} -> {next_height} at {nx},{ny}");
find_paths_to_nines(map, next_height, nx, ny, scores) capture_scores(map, next_height, nx, ny, scores)
} }
} }
} }
fn part2(input: &str) -> usize { fn part2(input: &str) -> usize {
0 println!("{input}");
let mut sum = 0;
let map: Vec<Vec<u8>> = input
.lines()
.map(|l| l.bytes().map(|b| b - b'0').collect())
.collect();
for (y, row) in map.iter().enumerate() {
for (x, height) in row.iter().enumerate() {
if *height == 0 {
sum += find_paths_to_nines(&map, *height, x, y);
}
println!("{x} {y} {height}");
}
}
sum
}
fn find_paths_to_nines(map: &Vec<Vec<u8>>, height: u8, x: usize, y: usize) -> usize {
let mut sum = 0;
if height == 9 {
return 1;
}
for (nx, ny) in [
(x + 1, y),
(x.saturating_sub(1), y),
(x, y + 1),
(x, y.saturating_sub(1)),
] {
if nx >= map[0].len() || ny >= map.len() {
continue;
}
let next_height = map[ny][nx];
if next_height.saturating_sub(height) == 1 {
println!("{height} -> {next_height} at {nx},{ny}");
sum += find_paths_to_nines(map, next_height, nx, ny)
}
}
sum
} }
#[cfg(test)] #[cfg(test)]
@ -73,6 +110,6 @@ mod tests {
01329801 01329801
10456732"#; 10456732"#;
assert_eq!(part1(input), 36); assert_eq!(part1(input), 36);
assert_eq!(part2(input), 0); assert_eq!(part2(input), 81);
} }
} }