import fileinput from adventofcode.intcode import Interpreter DIRECTIONS = { 1: -1j, # N 2: 1j, # S 3: -1, # W 4: 1, # E } REVERSE = { 1: 2, 2: 1, 3: 4, 4: 3} def main(inp): program = [int(x) for x in inp.split(",")] interpreter = Interpreter(program) goal_pos, dist_from_start, visited = find_goal(interpreter) print("Part 1:", dist_from_start) print("Part 2:", fill_oxygen(visited, goal_pos)) def find_goal(interpreter): visited = {} explore_maze(interpreter, 0, 0, visited) for pos, (dist, is_goal) in visited.items(): if is_goal: return pos, dist, visited assert False, "unreachable" def explore_maze(interpreter, pos, dist, visited, is_goal=False): """ Recursively explore the maze in DFS order to find the goal position and its distance from the start position. """ visited[pos] = (dist, is_goal) for cmd, direction in DIRECTIONS.items(): neighbor = pos + direction if neighbor in visited: continue res = send_to_bot(interpreter, cmd) if res == 0: continue explore_maze(interpreter, neighbor, dist + 1, visited, is_goal=res == 2) send_to_bot(interpreter, REVERSE[cmd]) def fill_oxygen(graph, start_pos): """ BFS the map from part1 starting from the oxygen pos, keeping track of the max distance. """ queue = [(start_pos, 0)] # pos, dist from start node visited = {start_pos} max_dist = 0 while queue != []: cur, dist = queue.pop(0) max_dist = max(dist, max_dist) for direction in DIRECTIONS.values(): neighbor = cur + direction if neighbor not in visited and neighbor in graph: visited.add(neighbor) queue.append((neighbor, dist + 1)) return max_dist def send_to_bot(interpreter, cmd): interpreter.stdin.append(cmd) interpreter.interpret(break_on_input=True) assert not interpreter.halted res = interpreter.stdout.pop() return res if __name__ == '__main__': with fileinput.input() as f: main(next(f))