Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use grid::Grid;
- #[inline(always)]
- fn solve(grid: &Grid<usize>) -> usize {
- grid.iter().enumerate()
- .filter_map(|(trailhead, c)| {
- if *c == 0 {
- let x = trailhead % grid.cols();
- let y = trailhead / grid.cols();
- Some(check_cell(grid, &usize::MAX, x, y))
- } else {
- None
- }
- })
- .sum()
- }
- fn check_cell(grid: &Grid<usize>, prev: &usize, x: usize, y: usize) -> usize {
- let mut count = 0;
- if let Some(cell) = grid.get(y, x) {
- if (cell > prev && cell - prev == 1) || prev == &usize::MAX {
- if *cell == 9 {
- // set.insert((x, y));
- count += 1;
- } else {
- count += check_cell(grid, &cell, x + 1, y);
- count += check_cell(grid, &cell, x, y + 1);
- if x > 0 {
- count += check_cell(grid, &cell, x - 1, y);
- }
- if y > 0 {
- count += check_cell(grid, &cell, x, y - 1);
- }
- }
- }
- }
- count
- }
- fn main() {
- let input = include_str!("../input.txt")
- .lines()
- .map(|l| l.chars().map(|c| c.to_digit(10).unwrap() as usize).collect())
- .collect::<Vec<Vec<usize>>>();
- let cols = input.len();
- let grid = Grid::from_vec(input.into_iter().flatten().collect(), cols);
- let time = std::time::Instant::now();
- let answer = solve(&grid);
- println!("Time elapsed: {:?}", time.elapsed());
- println!("Answer: {}", answer);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement