from heapq import heappop, heappush
from math import inf, isfinite


def cheapest_path(width, height, walls, costs, start, goal):
    """Four-direction grid; cost is paid when entering a cell."""
    def inside(cell):
        x, y = cell
        return 0 <= x < width and 0 <= y < height

    if width <= 0 or height <= 0:
        raise ValueError("Grid dimensions must be positive")
    if not inside(start) or not inside(goal):
        raise ValueError("Start and goal must be inside the grid")
    if any(not isfinite(c) or c < 0 for c in costs.values()):
        raise ValueError("Costs must be finite and non-negative")
    if start in walls or goal in walls:
        return [], inf

    best = {start: 0}
    parent = {start: None}
    frontier = [(0, start)]
    while frontier:
        total, cell = heappop(frontier)
        if total != best[cell]:
            continue  # A cheaper entry superseded this one.
        if cell == goal:
            route = []
            while cell is not None:
                route.append(cell)
                cell = parent[cell]
            return route[::-1], total
        x, y = cell
        for nxt in ((x + 1, y), (x, y - 1), (x, y + 1), (x - 1, y)):
            if not inside(nxt) or nxt in walls:
                continue
            candidate = total + costs.get(nxt, 1)
            if candidate < best.get(nxt, inf):
                best[nxt] = candidate
                parent[nxt] = cell
                heappush(frontier, (candidate, nxt))
    return [], inf


def run_checks():
    start, goal = (0, 1), (4, 1)
    costs = {(1, 1): 9, (2, 1): 9, (3, 1): 9}
    route, total = cheapest_path(5, 3, set(), costs, start, goal)
    assert total == 6 and len(route) - 1 == 6
    assert route[0] == start and route[-1] == goal
    assert all(abs(a[0] - b[0]) + abs(a[1] - b[1]) == 1
               for a, b in zip(route, route[1:]))
    assert sum(costs.get(cell, 1) for cell in route[1:]) == total
    walls = {(2, y) for y in range(3)}
    assert cheapest_path(5, 3, walls, costs, start, goal) == ([], inf)
    assert cheapest_path(5, 3, {goal}, costs, start, goal) == ([], inf)
    assert cheapest_path(5, 3, set(), costs, start, start) == ([start], 0)
    zero_cost = {(x, y): 0 for x in range(5) for y in range(3)}
    assert cheapest_path(5, 3, set(), zero_cost, start, goal)[1] == 0
    assert cheapest_path(5, 3, set(), {}, start, goal)[1] == 4
    for bad in (-1, float("nan"), float("inf")):
        try:
            cheapest_path(5, 3, set(), {goal: bad}, start, goal)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid cost accepted")
    print("Moves:", len(route) - 1)
    print("Cost:", total)
    print("Path:", route)
    print("All checks passed")


if __name__ == "__main__":
    run_checks()
