diff options
author | mhsn <mail@mhsn.net> | 2025-09-02 18:59:18 +0000 |
---|---|---|
committer | mhsn <mail@mhsn.net> | 2025-09-02 18:59:18 +0000 |
commit | 56460d6df1324903ce429c619620af33c473dad0 (patch) | |
tree | 41c0147192cabdde7cf305c45dff0997fa633843 /2024/10/rust/src | |
parent | 8109ce105623d1baf0578c56f5cd8c0a865c9ad9 (diff) | |
download | aoc-56460d6df1324903ce429c619620af33c473dad0.tar.gz aoc-56460d6df1324903ce429c619620af33c473dad0.zip |
24-10-rs both
Diffstat (limited to '2024/10/rust/src')
-rw-r--r-- | 2024/10/rust/src/main.rs | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/2024/10/rust/src/main.rs b/2024/10/rust/src/main.rs new file mode 100644 index 0000000..b5b3825 --- /dev/null +++ b/2024/10/rust/src/main.rs @@ -0,0 +1,52 @@ +use std::collections::HashSet; +use std::io; + +fn main() -> io::Result<()> { + let grid: Vec<Vec<u8>> = io::stdin() + .lines() + .flatten() + .map(|s| s.chars().map(|c| c.to_digit(10).unwrap() as u8).collect()) + .collect(); + + let starts = grid + .iter() + .enumerate() + .flat_map(|(y, row)| row.iter().enumerate().map(move |(x, d)| (x, y, d))) + .filter_map(|(x, y, d)| (*d == 0).then_some((y, x))) + .collect::<Vec<_>>(); + + let silver: usize = starts.iter().map(|&s| trailheads(s, &grid, false)).sum(); + let gold: usize = starts.iter().map(|&s| trailheads(s, &grid, true)).sum(); + + println!("silver: {silver}"); + println!("gold: {gold}"); + + return Ok(()); +} + +fn trailheads(start: (usize, usize), grid: &Vec<Vec<u8>>, count_paths: bool) -> usize { + let mut seen = HashSet::new(); + let mut tot = 0; + let mut q = vec![start]; + + while let Some(curr @ (y, x)) = q.pop() { + seen.insert(curr); + let h = grid[y][x]; + if h == 9 { + tot += 1; + continue; + } + + [ + ((y + 1).min(grid.len() - 1), x), + (y, (x + 1).min(grid[0].len() - 1)), + (y.saturating_sub(1), x), + (y, x.saturating_sub(1)), + ] + .iter() + .filter(|&&(ny, nx)| grid[ny][nx] == h + 1) + .filter(|next| count_paths || !seen.contains(next)) + .for_each(|&n| q.push(n)); + } + tot +} |