"""Breadth-first search (BFS) and unweighted shortest paths.

Idea
----
Explore the graph in "rings": first the start node, then all its neighbours,
then their unvisited neighbours, and so on, using a FIFO queue. Because nodes
are discovered in order of distance, the first time BFS reaches a node it has
found a shortest path (fewest edges) to it.

Mark nodes as visited when you *enqueue* them, not when you dequeue them,
or the same node can sit in the queue many times.

Complexity
----------
Time:  O(V + E)
Space: O(V)
"""

from collections import deque
from collections.abc import Hashable, Mapping, Sequence
from typing import TypeVar

N = TypeVar("N", bound=Hashable)


def bfs_order(graph: Mapping[N, Sequence[N]], start: N) -> list[N]:
    """Return nodes in the order BFS visits them."""
    seen = {start}
    order: list[N] = []
    queue = deque([start])
    while queue:
        node = queue.popleft()
        order.append(node)
        for nxt in graph.get(node, ()):
            if nxt not in seen:
                seen.add(nxt)
                queue.append(nxt)
    return order


def shortest_path(graph: Mapping[N, Sequence[N]], start: N, goal: N) -> list[N] | None:
    """Return a path with the fewest edges from ``start`` to ``goal``, or None."""
    parent: dict[N, N | None] = {start: None}
    queue = deque([start])
    while queue:
        node = queue.popleft()
        if node == goal:
            path = [node]
            while parent[path[-1]] is not None:
                path.append(parent[path[-1]])  # type: ignore[arg-type]
            return path[::-1]
        for nxt in graph.get(node, ()):
            if nxt not in parent:
                parent[nxt] = node
                queue.append(nxt)
    return None
