Advertisement
Guest User

Untitled

a guest
Dec 12th, 2024
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.53 KB | None | 0 0
  1. use grid::*;
  2.  
  3. fn main() {
  4.     let mut input = include_str!("../input.txt").lines().peekable();
  5.     let width = input.peek().unwrap().len();
  6.     let mut grid = Grid::from_vec(input.flat_map(|l| l.chars()).collect(), width);
  7.  
  8.     let time = std::time::Instant::now();
  9.  
  10.     let mut sum = 0;
  11.  
  12.     for i in 0..width * grid.rows() {
  13.         let x = (i % width) as i16;
  14.         let y = (i / width) as i16;
  15.  
  16.         let cell = grid[(y as usize, x as usize)];
  17.  
  18.         if cell == '#' {
  19.             continue;
  20.         }
  21.  
  22.         let mut cells = Vec::new();
  23.         let perimeter = explore(x, y, cell, &mut grid, &mut cells);
  24.  
  25.         sum += cells.len() as u32 * perimeter;
  26.     }
  27.  
  28.     println!("Time: {:?}", time.elapsed());
  29.     println!("🪵 answer: {:#?}", sum);
  30. }
  31.  
  32. fn explore(
  33.     x: i16,
  34.     y: i16,
  35.     cell: char,
  36.     grid: &mut Grid<char>,
  37.     cells: &mut Vec<(u16, u16)>,
  38. ) -> u32 {
  39.     if cells.iter().any(|&(cy, cx)| cy as i16 == y && cx as i16 == x) {
  40.         return 0;
  41.     }
  42.  
  43.     if let Some(other) = grid.get(y, x) {
  44.         if *other == cell {
  45.             cells.push((y as u16, x as u16));
  46.             grid[(y as usize, x as usize)] = '#';
  47.  
  48.             let val = explore(x, y - 1, cell, grid, cells) +
  49.                 explore(x + 1, y, cell, grid, cells) +
  50.                 explore(x, y + 1, cell, grid, cells) +
  51.                 explore(x - 1, y, cell, grid, cells);
  52.  
  53.             return val;
  54.  
  55.         } else {
  56.             return 1;
  57.         }
  58.     }
  59.  
  60.     1 // no cell means edge. That adds 1 perimeter
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement