1use std::collections::VecDeque;
13
14use crate::util::hash::*;
15use crate::util::intcode::*;
16use crate::util::parse::*;
17use crate::util::point::*;
18
19type Input = (FastSet<Point>, Point);
20
21pub fn parse(input: &str) -> Input {
23 let code: Vec<_> = input.iter_signed().collect();
24 let mut computer = Computer::new(&code);
25
26 let mut paths = FastSet::with_capacity(1_000);
27 let mut walls = FastSet::with_capacity(1_000);
28
29 let mut direction = RIGHT;
30 let mut position = ORIGIN;
31 let mut oxygen_system = ORIGIN;
32
33 loop {
34 let next = position + direction;
35
36 if walls.contains(&next) {
37 direction = direction.counter_clockwise();
38 continue;
39 }
40
41 computer.input(match direction {
42 UP => 1,
43 DOWN => 2,
44 LEFT => 3,
45 RIGHT => 4,
46 _ => unreachable!(),
47 });
48
49 match computer.run() {
50 State::Output(0) => {
51 walls.insert(next);
52 direction = direction.counter_clockwise();
53 }
54 State::Output(result) => {
55 position = next;
56 paths.insert(next);
57 direction = direction.clockwise();
58
59 if result == 2 {
60 oxygen_system = position;
61 }
62 if position == ORIGIN {
63 break;
64 }
65 }
66 _ => unreachable!(),
67 }
68 }
69
70 (paths, oxygen_system)
71}
72
73pub fn part1(input: &Input) -> i32 {
75 let (maze, oxygen_system) = input.clone();
76 bfs(maze, ORIGIN, Some(oxygen_system))
77}
78
79pub fn part2(input: &Input) -> i32 {
81 let (maze, oxygen_system) = input.clone();
82 bfs(maze, oxygen_system, None)
83}
84
85fn bfs(mut maze: FastSet<Point>, start: Point, end: Option<Point>) -> i32 {
87 let mut todo = VecDeque::from([(start, 0)]);
88 let mut result = 0;
89
90 maze.remove(&start);
91
92 while let Some((point, cost)) = todo.pop_front() {
93 result = cost;
94
95 if end == Some(point) {
96 break;
97 }
98
99 for next in ORTHOGONAL.map(|o| point + o) {
100 if maze.remove(&next) {
101 todo.push_back((next, cost + 1));
102 }
103 }
104 }
105
106 result
107}