From a16162adfdf3f2018194edd42052cc72febc1ab6 Mon Sep 17 00:00:00 2001 From: Sebastian Mark Date: Fri, 6 Dec 2024 14:05:07 +0100 Subject: [PATCH] update 2024/day6 better placing of obstacles, no more brute force --- 2024/06/main.py | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/2024/06/main.py b/2024/06/main.py index 2f1a807..507c212 100644 --- a/2024/06/main.py +++ b/2024/06/main.py @@ -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,17 +90,16 @@ 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]): - if (col, row) == guard: - continue - new_maze = deepcopy(maze) - new_maze[row][col] = "#" - _, loop = move_guard(new_maze, guard) - if loop: - count += 1 + # 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) + if loop: + count += 1 print("Loop options: %d" % count)