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