"""Depth-first search (DFS), iterative and recursive, plus cycle detection.

Idea
----
Go as deep as possible along one branch before backtracking. A stack (or the
call stack, in the recursive version) remembers where to come back to.

DFS is the basis of topological sorting, cycle detection, connected
components, and finding bridges and articulation points.

Cycle detection in a *directed* graph uses three colours: white (unvisited),
grey (on the current DFS path) and black (finished). Reaching a grey node
means you found a back edge, i.e. a cycle.

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

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

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


def dfs_order(graph: Mapping[N, Sequence[N]], start: N) -> list[N]:
    """Iterative pre-order DFS that visits neighbours in listed order."""
    seen: set[N] = set()
    order: list[N] = []
    stack = [start]
    while stack:
        node = stack.pop()
        if node in seen:
            continue
        seen.add(node)
        order.append(node)
        # Push in reverse so the first neighbour is explored first.
        for nxt in reversed(graph.get(node, ())):
            if nxt not in seen:
                stack.append(nxt)
    return order


def dfs_recursive(graph: Mapping[N, Sequence[N]], start: N) -> list[N]:
    """Recursive pre-order DFS (same order as ``dfs_order``)."""
    order: list[N] = []
    seen: set[N] = set()

    def visit(node: N) -> None:
        seen.add(node)
        order.append(node)
        for nxt in graph.get(node, ()):
            if nxt not in seen:
                visit(nxt)

    visit(start)
    return order


def has_cycle(graph: Mapping[N, Sequence[N]]) -> bool:
    """Return True if the directed graph contains a cycle."""
    WHITE, GREY, BLACK = 0, 1, 2
    colour: dict[N, int] = {}

    def visit(node: N) -> bool:
        colour[node] = GREY
        for nxt in graph.get(node, ()):
            state = colour.get(nxt, WHITE)
            if state == GREY or (state == WHITE and visit(nxt)):
                return True
        colour[node] = BLACK
        return False

    return any(colour.get(n, WHITE) == WHITE and visit(n) for n in list(graph))
