|
| 1 | +use adventofcode::grid::Grid; |
| 2 | +use itertools::Itertools; |
| 3 | +use std::{ |
| 4 | + collections::VecDeque, |
| 5 | + io::{self, BufRead}, |
| 6 | +}; |
| 7 | + |
| 8 | +fn main() { |
| 9 | + let (x, y) = solve(io::stdin().lock(), 71, 1024); |
| 10 | + println!("{x},{y}"); |
| 11 | +} |
| 12 | + |
| 13 | +fn solve(input: impl BufRead, size: usize, bytes: usize) -> (usize, usize) { |
| 14 | + let mut grid = Grid::new(size, size, '.'); |
| 15 | + input |
| 16 | + .lines() |
| 17 | + .map(|line| -> (usize, usize) { |
| 18 | + line.expect("IO error") |
| 19 | + .split(',') |
| 20 | + .flat_map(|s| s.parse()) |
| 21 | + .collect_tuple() |
| 22 | + .unwrap() |
| 23 | + }) |
| 24 | + .enumerate() |
| 25 | + .find(|&(i, (x, y))| { |
| 26 | + let pos = grid.get_coords(x, y).unwrap(); |
| 27 | + grid.set(pos, '#'); |
| 28 | + |
| 29 | + i > bytes && !is_reachable(&grid) |
| 30 | + }) |
| 31 | + .unwrap() |
| 32 | + .1 |
| 33 | +} |
| 34 | + |
| 35 | +fn is_reachable(grid: &Grid) -> bool { |
| 36 | + let mut queue = VecDeque::new(); |
| 37 | + let mut dist = vec![usize::MAX; grid.len()]; |
| 38 | + dist[0] = 0; |
| 39 | + queue.push_back(grid.pos(0)); |
| 40 | + while let Some(pos) = queue.pop_front() { |
| 41 | + queue.extend( |
| 42 | + pos.neighbors(grid) |
| 43 | + .filter(|&next| next.value() == '.') |
| 44 | + .filter(|&next| { |
| 45 | + let d = dist[next.index()]; |
| 46 | + if d == usize::MAX { |
| 47 | + dist[next.index()] = dist[pos.index()] + 1; |
| 48 | + true |
| 49 | + } else { |
| 50 | + false |
| 51 | + } |
| 52 | + }), |
| 53 | + ); |
| 54 | + } |
| 55 | + |
| 56 | + dist[grid.len() - 1] < usize::MAX |
| 57 | +} |
| 58 | + |
| 59 | +#[cfg(test)] |
| 60 | +mod test { |
| 61 | + use super::solve; |
| 62 | + use std::{ |
| 63 | + fs::File, |
| 64 | + io::{self, BufReader}, |
| 65 | + }; |
| 66 | + |
| 67 | + fn open(path: &str) -> io::Result<BufReader<File>> { |
| 68 | + let file = File::open(path)?; |
| 69 | + Ok(BufReader::new(file)) |
| 70 | + } |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn test_example() { |
| 74 | + let input = open("input/day18/example.txt").expect("Missing file"); |
| 75 | + assert_eq!((6, 1), solve(input, 7, 12)); |
| 76 | + } |
| 77 | + |
| 78 | + #[test] |
| 79 | + fn test_input() { |
| 80 | + let input = open("input/day18/input.txt").expect("Missing file"); |
| 81 | + assert_eq!((62, 6), solve(input, 71, 1024)); |
| 82 | + } |
| 83 | +} |
0 commit comments