1
0
Fork 0
adventofcode/2024/06/main.py

109 lines
2.6 KiB
Python
Raw Normal View History

2024-12-06 12:05:45 +00:00
#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# Author: Sebastian Mark
# CC-BY-SA (https://creativecommons.org/licenses/by-sa/4.0/deed.de)
# pylint: disable=missing-module-docstring,missing-function-docstring,consider-using-f-string
from copy import deepcopy
def readinput() -> str:
with open("input", "r", encoding="utf-8") as file:
lines = [list(line.strip()) for line in file]
return lines
def find_guard(maze: list) -> tuple:
for idx, row in enumerate(maze):
try:
x = row.index("^")
y = idx
except ValueError:
pass
else:
return (x, y)
return tuple(-1, -1)
2024-12-06 14:43:33 +00:00
def move_guard(maze: list, guard_pos: tuple) -> tuple[int, bool, dict]:
2024-12-06 12:05:45 +00:00
width = len(maze[0])
height = len(maze)
path_history = {}
# remember the start position as visited
visited = set()
2024-12-06 14:43:33 +00:00
visited.add(guard_pos)
2024-12-06 12:05:45 +00:00
# start upwards
direction = (0, -1)
while True:
# get next position
nxt = (
2024-12-06 14:43:33 +00:00
guard_pos[0] + direction[0],
guard_pos[1] + direction[1],
2024-12-06 12:05:45 +00:00
)
# check borders
if not (0 <= nxt[0] < width and 0 <= nxt[1] < height):
2024-12-06 14:43:33 +00:00
visited.add(guard_pos)
2024-12-06 12:05:45 +00:00
break
# check for obstacle and rotate clockwise
if maze[nxt[1]][nxt[0]] == "#":
direction = (-direction[1], direction[0])
continue
# loop detection
# (has the guard been here and walking in the same direction?)
if nxt not in path_history:
2024-12-06 14:43:33 +00:00
path_history[nxt] = (guard_pos, direction)
elif path_history[nxt] == (guard_pos, direction):
return 0, True, {}
2024-12-06 12:05:45 +00:00
# mark spot as visited and move guard
2024-12-06 14:43:33 +00:00
visited.add(guard_pos)
guard_pos = nxt
2024-12-06 12:05:45 +00:00
return len(visited), False, path_history
2024-12-06 12:05:45 +00:00
def print_maze(maze: list):
for row in maze:
print("".join(row))
print("-")
def main():
# part 1
maze = readinput()
2024-12-06 14:43:33 +00:00
guard_pos = find_guard(maze)
count, _, guard_path = move_guard(maze, guard_pos)
2024-12-06 12:05:45 +00:00
print("Guard positions: %d" % count)
# part 2
count = 0
maze = readinput()
2024-12-06 14:43:33 +00:00
guard_pos = find_guard(maze)
2024-12-06 12:05:45 +00:00
# place an obstacle at every position in the guards path
# then check new maze for loop
for col, row in guard_path:
2024-12-06 14:43:33 +00:00
if (col, row) == guard_pos:
continue
new_maze = deepcopy(maze)
new_maze[row][col] = "#"
2024-12-06 14:43:33 +00:00
_, loop, _ = move_guard(new_maze, guard_pos)
if loop:
count += 1
2024-12-06 12:05:45 +00:00
print("Loop options: %d" % count)
if __name__ == "__main__":
main()