update 2024/day6
better placing of obstacles, no more brute force
This commit is contained in:
parent
7c4e98ebcf
commit
a16162adfd
1 changed files with 14 additions and 15 deletions
|
@ -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)
|
||||
|
||||
|
|
Loading…
Reference in a new issue