|
| 1 | +use std::collections::VecDeque; |
| 2 | + |
| 3 | +use aoc_utils::*; |
| 4 | + |
| 5 | +advent_of_code::solution!(20); |
| 6 | + |
| 7 | +#[cfg(not(test))] |
| 8 | +const SAVE_CUTOFF: usize = 100; |
| 9 | +#[cfg(test)] |
| 10 | +const SAVE_CUTOFF: usize = 50; |
| 11 | + |
| 12 | +fn find_path(start: Point, end: Point, map: &[Vec<char>]) -> Vec<Point> { |
| 13 | + let bounds = Bounds(map.len() - 1, map[0].len() - 1); |
| 14 | + let seen = &mut vec![vec![false; bounds.1 + 1]; bounds.0 + 1]; |
| 15 | + seen[start.0][start.1] = true; |
| 16 | + let mut queue = VecDeque::new(); |
| 17 | + let mut path = Vec::new(); |
| 18 | + queue.push_back(start); |
| 19 | + while !queue.is_empty() { |
| 20 | + let curr = queue.pop_front().unwrap(); |
| 21 | + path.push(curr); |
| 22 | + if curr == end { |
| 23 | + break; |
| 24 | + } |
| 25 | + Dir::neighbors(curr, bounds).into_iter().for_each(|p| { |
| 26 | + if !seen[p.0][p.1] { |
| 27 | + seen[p.0][p.1] = true; |
| 28 | + if map[p.0][p.1] != '#' { |
| 29 | + queue.push_back(p); |
| 30 | + } |
| 31 | + } |
| 32 | + }); |
| 33 | + } |
| 34 | + path |
| 35 | +} |
| 36 | + |
| 37 | +fn find_cheats(path: &[Point], max_dist: usize) -> u64 { |
| 38 | + path.iter() |
| 39 | + .enumerate() |
| 40 | + .take(path.len() - SAVE_CUTOFF - 1) |
| 41 | + .fold(0, |mut acc, (i, p)| { |
| 42 | + path.iter() |
| 43 | + .enumerate() |
| 44 | + .skip(i + SAVE_CUTOFF + 2) |
| 45 | + .for_each(|(j, p2)| { |
| 46 | + let d = dist(*p, *p2); |
| 47 | + if j - i - d >= SAVE_CUTOFF && d <= max_dist { |
| 48 | + acc += 1; |
| 49 | + } |
| 50 | + }); |
| 51 | + acc |
| 52 | + }) |
| 53 | +} |
| 54 | + |
| 55 | +pub fn part_one(input: &str) -> Option<u64> { |
| 56 | + let map = input.c_map(); |
| 57 | + let start = find_point(&map, 'S'); |
| 58 | + let end = find_point(&map, 'E'); |
| 59 | + let path = find_path(start, end, &map); |
| 60 | + Some(find_cheats(&path, 2)) |
| 61 | +} |
| 62 | + |
| 63 | +pub fn part_two(input: &str) -> Option<u64> { |
| 64 | + let map = input.c_map(); |
| 65 | + let start = find_point(&map, 'S'); |
| 66 | + let end = find_point(&map, 'E'); |
| 67 | + let path = find_path(start, end, &map); |
| 68 | + Some(find_cheats(&path, 20)) |
| 69 | +} |
| 70 | + |
| 71 | +#[cfg(test)] |
| 72 | +mod tests { |
| 73 | + use super::*; |
| 74 | + |
| 75 | + #[test] |
| 76 | + fn test_part_one() { |
| 77 | + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); |
| 78 | + assert_eq!(result, Some(1)); |
| 79 | + } |
| 80 | + |
| 81 | + #[test] |
| 82 | + fn test_part_two() { |
| 83 | + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); |
| 84 | + assert_eq!(result, Some(285)); |
| 85 | + } |
| 86 | +} |
0 commit comments