Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use grid::*;
- fn main() {
- let mut input = include_str!("../input.txt").lines().peekable();
- let width = input.peek().unwrap().len();
- let mut grid = Grid::from_vec(input.flat_map(|l| l.chars()).collect(), width);
- let time = std::time::Instant::now();
- let mut sum = 0;
- for i in 0..width * grid.rows() {
- let x = (i % width) as i16;
- let y = (i / width) as i16;
- let cell = grid[(y as usize, x as usize)];
- if cell == '#' {
- continue;
- }
- let mut cells = Vec::new();
- let perimeter = explore(x, y, cell, &mut grid, &mut cells);
- sum += cells.len() as u32 * perimeter;
- }
- println!("Time: {:?}", time.elapsed());
- println!("🪵 answer: {:#?}", sum);
- }
- fn explore(
- x: i16,
- y: i16,
- cell: char,
- grid: &mut Grid<char>,
- cells: &mut Vec<(u16, u16)>,
- ) -> u32 {
- if cells.iter().any(|&(cy, cx)| cy as i16 == y && cx as i16 == x) {
- return 0;
- }
- if let Some(other) = grid.get(y, x) {
- if *other == cell {
- cells.push((y as u16, x as u16));
- grid[(y as usize, x as usize)] = '#';
- let val = explore(x, y - 1, cell, grid, cells) +
- explore(x + 1, y, cell, grid, cells) +
- explore(x, y + 1, cell, grid, cells) +
- explore(x - 1, y, cell, grid, cells);
- return val;
- } else {
- return 1;
- }
- }
- 1 // no cell means edge. That adds 1 perimeter
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement