Guest User

Untitled

a guest
Dec 10th, 2024
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.79 KB | None | 0 0
  1. use grid::Grid;
  2. use std::collections::HashSet;
  3.  
  4. fn solve(grid: &Grid<u32>) -> usize {
  5.     let trailheads = grid.iter().enumerate()
  6.         .filter_map(|(index, c)| (*c == 0).then_some(index))
  7.         .collect::<Vec<usize>>();
  8.  
  9.     let mut sum = 0;
  10.  
  11.     for trailhead in &trailheads {
  12.  
  13.         let x = (trailhead % grid.cols()) as i32;
  14.         let y = (trailhead / grid.cols()) as i32;
  15.         let cell = grid.get(y, x).unwrap();
  16.  
  17.         let mut set = HashSet::new();
  18.         set.extend(check_cell(grid, &cell, x + 1, y));
  19.         set.extend(check_cell(grid, &cell, x, y + 1));
  20.         set.extend(check_cell(grid, &cell, x - 1, y));
  21.         set.extend(check_cell(grid, &cell, x, y - 1));
  22.  
  23.         sum += set.len();
  24.     }
  25.  
  26.     sum
  27. }
  28.  
  29. fn check_cell(grid: &Grid<u32>, prev: &u32, x: i32, y: i32) -> HashSet<(i32, i32)> {
  30.     let mut set = HashSet::new();
  31.  
  32.     if let Some(cell) = grid.get(y, x) {
  33.         if cell > prev && cell - prev == 1 {
  34.             if *cell == 9 {
  35.                 set.insert((x, y));
  36.             } else {
  37.                 set.extend(check_cell(grid, &cell, x + 1, y));
  38.                 set.extend(check_cell(grid, &cell, x, y + 1));
  39.                 set.extend(check_cell(grid, &cell, x - 1, y));
  40.                 set.extend(check_cell(grid, &cell, x, y - 1));
  41.             }
  42.         }
  43.     }
  44.  
  45.     set
  46. }
  47.  
  48. fn main() {
  49.     let input = include_str!("../input.txt")
  50.         .lines()
  51.         .map(|l| l.chars().map(|c| c.to_digit(10).unwrap()).collect())
  52.         .collect::<Vec<Vec<u32>>>();
  53.     let cols = input.len();
  54.     let grid = Grid::from_vec(input.into_iter().flatten().collect(), cols);
  55.  
  56.     let time = std::time::Instant::now();
  57.  
  58.     let answer = solve(&grid);
  59.  
  60.     println!("Time elapsed: {:?}", time.elapsed());
  61.     println!("Answer: {}", answer);
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment