|
| 1 | +#![feature(test)] |
| 2 | + |
| 3 | +use std::collections::VecDeque; |
| 4 | + |
| 5 | +use aoc::grid::Direction; |
| 6 | +use itertools::Itertools; |
| 7 | + |
| 8 | +struct Input { |
| 9 | + width: usize, |
| 10 | + height: usize, |
| 11 | + grid: Vec<usize>, |
| 12 | + prefix_len: usize, |
| 13 | + bytes: Vec<(usize, usize)>, |
| 14 | +} |
| 15 | + |
| 16 | +fn setup(input: &str) -> Input { |
| 17 | + let mut lines = input.trim().lines().peekable(); |
| 18 | + let (width, height, prefix_len) = match lines.next_if(|l| l.starts_with('#')) { |
| 19 | + Some(line) => line |
| 20 | + .trim_start_matches('#') |
| 21 | + .split_whitespace() |
| 22 | + .map(|n| n.parse().unwrap()) |
| 23 | + .collect_tuple() |
| 24 | + .unwrap(), |
| 25 | + None => (71, 71, 1024), |
| 26 | + }; |
| 27 | + |
| 28 | + let bytes = lines |
| 29 | + .map(|l| { |
| 30 | + l.split(',') |
| 31 | + .map(|n| n.parse().unwrap()) |
| 32 | + .collect_tuple() |
| 33 | + .unwrap() |
| 34 | + }) |
| 35 | + .collect::<Vec<_>>(); |
| 36 | + |
| 37 | + let mut grid = vec![usize::MAX; width * height]; |
| 38 | + for (i, &(x, y)) in bytes.iter().enumerate() { |
| 39 | + grid[y * width + x] = i; |
| 40 | + } |
| 41 | + |
| 42 | + Input { |
| 43 | + width, |
| 44 | + height, |
| 45 | + grid, |
| 46 | + prefix_len, |
| 47 | + bytes, |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +fn bfs(input: &Input, prefix_len: usize) -> Option<usize> { |
| 52 | + let mut queue = VecDeque::from([(0, 0, 0)]); |
| 53 | + let mut visited = vec![false; input.width * input.height]; |
| 54 | + while let Some((d, x, y)) = queue.pop_front() { |
| 55 | + let idx = y * input.width + x; |
| 56 | + if std::mem::replace(&mut visited[idx], true) { |
| 57 | + continue; |
| 58 | + } |
| 59 | + |
| 60 | + if (x, y) == (input.width - 1, input.height - 1) { |
| 61 | + return Some(d); |
| 62 | + } |
| 63 | + |
| 64 | + queue.extend( |
| 65 | + Direction::iter() |
| 66 | + .flat_map(|d| d.step(x, y, input.width, input.height)) |
| 67 | + .filter(|&(nx, ny)| input.grid[ny * input.width + nx] >= prefix_len) |
| 68 | + .map(|(nx, ny)| (d + 1, nx, ny)), |
| 69 | + ); |
| 70 | + } |
| 71 | + |
| 72 | + None |
| 73 | +} |
| 74 | + |
| 75 | +fn part1(input: &Input) -> usize { |
| 76 | + bfs(input, input.prefix_len).unwrap() |
| 77 | +} |
| 78 | + |
| 79 | +fn part2(input: &Input) -> String { |
| 80 | + let mut left = 0; |
| 81 | + let mut right = input.bytes.len(); |
| 82 | + while left + 1 < right { |
| 83 | + let m = left.midpoint(right); |
| 84 | + match bfs(input, m) { |
| 85 | + Some(_) => left = m, |
| 86 | + None => right = m, |
| 87 | + } |
| 88 | + } |
| 89 | + debug_assert_eq!(left + 1, right); |
| 90 | + let (x, y) = input.bytes[right - 1]; |
| 91 | + format!("{x},{y}") |
| 92 | +} |
| 93 | + |
| 94 | +aoc::main!(2024, 18, ex: 1); |
0 commit comments