"""A* search on a grid.

Idea
----
Dijkstra expands nodes in order of distance from the start, g(n). A* orders
them by f(n) = g(n) + h(n), where the heuristic h(n) estimates the remaining
distance to the goal. If h never overestimates (it is *admissible*), A* still
returns a shortest path but explores far fewer nodes in the "wrong"
direction. With h = 0, A* is exactly Dijkstra.

On a 4-connected grid with unit moves, the Manhattan distance
|dr| + |dc| is admissible.

Complexity
----------
Time:  O(E log V) in the worst case (same as Dijkstra); usually much less
Space: O(V)

When to use
-----------
Path-finding in games, maps and robotics, whenever you have a good, cheap
lower bound on the remaining cost.
"""

import heapq
from collections.abc import Sequence

Cell = tuple[int, int]


def manhattan(a: Cell, b: Cell) -> int:
    return abs(a[0] - b[0]) + abs(a[1] - b[1])


def a_star(grid: Sequence[str], start: Cell, goal: Cell) -> list[Cell] | None:
    """Shortest 4-directional path avoiding '#' cells, or None if blocked."""
    rows, cols = len(grid), len(grid[0])
    g_score = {start: 0}
    parent: dict[Cell, Cell] = {}
    heap = [(manhattan(start, goal), 0, start)]
    while heap:
        _, g, cell = heapq.heappop(heap)
        if cell == goal:
            path = [cell]
            while path[-1] in parent:
                path.append(parent[path[-1]])
            return path[::-1]
        if g > g_score[cell]:
            continue  # stale entry
        r, c = cell
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != "#":
                ng = g + 1
                if ng < g_score.get((nr, nc), float("inf")):
                    g_score[(nr, nc)] = ng
                    parent[(nr, nc)] = cell
                    heapq.heappush(heap, (ng + manhattan((nr, nc), goal), ng, (nr, nc)))
    return None
