|
| 1 | +from GhostyUtils import aoc, pathfinding |
| 2 | +from GhostyUtils.grid import Grid |
| 3 | +from GhostyUtils.vec2 import Vec2, Dir |
| 4 | +from functools import partial |
| 5 | + |
| 6 | + |
| 7 | +def neighbours(pos: tuple[tuple[int], Dir], maze: Grid): |
| 8 | + pos, dir = pos |
| 9 | + return [(n, (Vec2(n) - Vec2(pos)).as_tuple()) |
| 10 | + for n in filter(lambda p: maze[p] != '#', maze.neighbours(pos, diagonal=False))] |
| 11 | + |
| 12 | + |
| 13 | +def cost(current: tuple[tuple[int], Dir], next_: tuple[tuple[int], Dir]): |
| 14 | + _, c_dir = current |
| 15 | + _, n_dir = next_ |
| 16 | + |
| 17 | + if c_dir == n_dir: |
| 18 | + return 1 |
| 19 | + elif Dir(n_dir) in {Dir(c_dir).turn_left(), Dir(c_dir).turn_right()}: |
| 20 | + return 1000 + 1 |
| 21 | + else: |
| 22 | + return 2001 |
| 23 | + |
| 24 | + |
| 25 | +def heuristic(next_pos: tuple[tuple[int], Dir], end: tuple[int]) -> int: |
| 26 | + next_pos, _ = next_pos |
| 27 | + return Vec2.manhattan_distance(next_pos, end) |
| 28 | + |
| 29 | + |
| 30 | +def early_out(current, end): |
| 31 | + return current[0] == end |
| 32 | + |
| 33 | + |
| 34 | +def main(): |
| 35 | + maze = Grid(aoc.read_lines()) |
| 36 | + start = (maze.find('S'), Dir.EAST.as_tuple()) |
| 37 | + end = maze.find('E') |
| 38 | + |
| 39 | + neighbours_func = partial(neighbours, maze=maze) |
| 40 | + early_out_func = partial(early_out, end=end) |
| 41 | + came_from, cost_so_far, last_pos = pathfinding.a_star(start, end, |
| 42 | + neighbours=neighbours_func, |
| 43 | + cost=cost, |
| 44 | + heuristic=heuristic, |
| 45 | + early_out=early_out_func) |
| 46 | + path = pathfinding.reconstruct_path(came_from, start, last_pos) |
| 47 | + |
| 48 | + if aoc.args.progress or aoc.args.verbose: |
| 49 | + path_overlay = {pos: {Dir.N: '^', Dir.S: 'v', Dir.E: '>', Dir.W: '<'}[Dir(dir)] |
| 50 | + for pos, dir in path} |
| 51 | + print(maze.render_with_overlays([path_overlay])) |
| 52 | + print(f"p1: {cost_so_far[last_pos]}") |
| 53 | + |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + main() |
0 commit comments