1
0
Fork 0

update 2024/day6

better placing of obstacles, no more brute force
This commit is contained in:
Sebastian Mark 2024-12-06 14:05:07 +01:00
parent 7c4e98ebcf
commit a16162adfd

View file

@ -28,7 +28,7 @@ def find_guard(maze: list) -> tuple:
return tuple(-1, -1)
def move_guard(maze: list, guard: tuple) -> tuple[int, bool]:
def move_guard(maze: list, guard: tuple) -> tuple[int, bool, dict]:
width = len(maze[0])
height = len(maze)
@ -63,13 +63,13 @@ def move_guard(maze: list, guard: tuple) -> tuple[int, bool]:
if nxt not in path_history:
path_history[nxt] = (guard, direction)
elif path_history[nxt] == (guard, direction):
return 0, True
return 0, True, {}
# mark spot as visited and move guard
visited.add(guard)
guard = nxt
return len(visited), False
return len(visited), False, path_history
def print_maze(maze: list):
@ -82,7 +82,7 @@ def main():
# part 1
maze = readinput()
guard = find_guard(maze)
count, _ = move_guard(maze, guard)
count, _, guard_path = move_guard(maze, guard)
print("Guard positions: %d" % count)
# part 2
@ -90,15 +90,14 @@ def main():
maze = readinput()
guard = find_guard(maze)
# brute force:
# place an obstacle everywhere (except the guards position)
for row, _ in enumerate(maze):
for col, _ in enumerate(maze[0]):
# place an obstacle at every position in the guards path
# then check new maze for loop
for col, row in guard_path:
if (col, row) == guard:
continue
new_maze = deepcopy(maze)
new_maze[row][col] = "#"
_, loop = move_guard(new_maze, guard)
_, loop, _ = move_guard(new_maze, guard)
if loop:
count += 1