day16 - corrected

This commit is contained in:
Stefan Harmuth 2024-12-16 09:46:05 +01:00
parent aedcdeaf39
commit fa14a46380

View File

@ -30,16 +30,35 @@ def get_best_score(grid: Grid) -> tuple[int, set[Coordinate]]:
def get_tiles_from_all_paths(grid: Grid) -> int:
target_score, target_path = get_best_score(grid)
target = Coordinate(grid.maxX - 1, 1)
path_scores = {}
score = 0
facing = Coordinate(1, 0)
pos = Coordinate(1, grid.maxY - 1)
visited = set()
while pos != target:
visited.add(pos)
for n in pos.getNeighbours(includeDiagonal=False):
if n not in target_path or n in visited:
continue
if n - pos != facing:
score += 1000
facing = n - pos
path_scores[pos] = score
pos = n
score += 1
queue = [(0, Coordinate(1, grid.maxY - 1), Coordinate(1, 0), {Coordinate(1, grid.maxY - 1)})]
# all_paths = set()
visited = {}
while queue:
score, pos, facing, path = heappop(queue)
if pos in visited and score > visited[pos][0] + 1000:
continue
if pos in target_path and pos in visited:
# print(f"{pos} in target_path and visited. {score=}, {visited[pos]=}, discarding {path=}")
if score <= visited[pos][0] or score == visited[pos][0] + 1000:
if pos in path_scores and pos in visited:
if score <= path_scores[pos]:
target_path |= path
continue
@ -58,9 +77,6 @@ def get_tiles_from_all_paths(grid: Grid) -> int:
add_turn = 1001 if n - pos != facing else 1
heappush(queue, (score + add_turn, n, n - pos, path | {n}))
for p in target_path:
grid.set(p, "O")
grid.print()
return len(target_path)