"""Week 12: Graph representation, BFS, DFS, components and cycle detection."""
from __future__ import annotations

from collections import defaultdict, deque
from typing import Dict, Hashable, Iterable, List, Optional, Set, Tuple


class Graph:
    """Adjacency-list graph. Undirected by default."""

    def __init__(self, edges: Iterable[Tuple[Hashable, Hashable]] = (), directed: bool = False):
        self.directed = directed
        self.adj: Dict[Hashable, List[Hashable]] = defaultdict(list)
        for u, v in edges:
            self.add_edge(u, v)

    def add_node(self, u: Hashable) -> None:
        self.adj.setdefault(u, [])

    def add_edge(self, u: Hashable, v: Hashable) -> None:
        self.adj[u].append(v)
        if self.directed:
            self.adj.setdefault(v, [])
        else:
            self.adj[v].append(u)

    def nodes(self) -> List[Hashable]:
        return list(self.adj)


def bfs_order(graph: Graph, start: Hashable) -> List[Hashable]:
    seen, order, queue = {start}, [], deque([start])
    while queue:
        u = queue.popleft()
        order.append(u)
        for v in graph.adj[u]:
            if v not in seen:
                seen.add(v)
                queue.append(v)
    return order


def dfs_order(graph: Graph, start: Hashable) -> List[Hashable]:
    """Iterative DFS that visits neighbours in insertion order (like the recursive version)."""
    seen, order, stack = set(), [], [start]
    while stack:
        u = stack.pop()
        if u in seen:
            continue
        seen.add(u)
        order.append(u)
        stack.extend(reversed(graph.adj[u]))
    return order


def shortest_path_unweighted(graph: Graph, start: Hashable, goal: Hashable) -> Optional[List[Hashable]]:
    """BFS with parent pointers; the first time goal is reached is via a shortest path."""
    parent = {start: None}
    queue = deque([start])
    while queue:
        u = queue.popleft()
        if u == goal:
            path = []
            while u is not None:
                path.append(u)
                u = parent[u]
            return path[::-1]
        for v in graph.adj[u]:
            if v not in parent:
                parent[v] = u
                queue.append(v)
    return None


def connected_components(graph: Graph) -> List[Set[Hashable]]:
    seen: Set[Hashable] = set()
    components = []
    for node in graph.nodes():
        if node not in seen:
            comp = set(bfs_order(graph, node))
            seen |= comp
            components.append(comp)
    return components


def has_cycle_undirected(graph: Graph) -> bool:
    """A visited neighbour that is not the parent closes a cycle."""
    seen: Set[Hashable] = set()
    for start in graph.nodes():
        if start in seen:
            continue
        stack = [(start, None)]
        seen.add(start)
        while stack:
            u, parent = stack.pop()
            skipped_parent = False
            for v in graph.adj[u]:
                if v == parent and not skipped_parent:
                    skipped_parent = True  # ignore the edge we came in on, once
                    continue
                if v in seen:
                    return True
                seen.add(v)
                stack.append((v, u))
    return False


def has_cycle_directed(graph: Graph) -> bool:
    """Three colours: white (unseen), grey (on the current path), black (finished)."""
    WHITE, GREY, BLACK = 0, 1, 2
    color = {u: WHITE for u in graph.nodes()}
    for start in graph.nodes():
        if color[start] != WHITE:
            continue
        stack = [(start, iter(graph.adj[start]))]
        color[start] = GREY
        while stack:
            u, it = stack[-1]
            v = next(it, None)
            if v is None:
                color[u] = BLACK
                stack.pop()
            elif color[v] == GREY:
                return True
            elif color[v] == WHITE:
                color[v] = GREY
                stack.append((v, iter(graph.adj[v])))
    return False


def is_bipartite(graph: Graph) -> bool:
    color: Dict[Hashable, int] = {}
    for start in graph.nodes():
        if start in color:
            continue
        color[start] = 0
        queue = deque([start])
        while queue:
            u = queue.popleft()
            for v in graph.adj[u]:
                if v not in color:
                    color[v] = 1 - color[u]
                    queue.append(v)
                elif color[v] == color[u]:
                    return False
    return True


def count_islands(grid: List[List[int]]) -> int:
    """Grid as an implicit graph: 4-directional neighbours of land cells."""
    rows, cols = len(grid), len(grid[0]) if grid else 0
    seen = set()
    islands = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] and (r, c) not in seen:
                islands += 1
                seen.add((r, c))
                stack = [(r, c)]
                while stack:
                    cr, cc = stack.pop()
                    for nr, nc in ((cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)):
                        if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] and (nr, nc) not in seen:
                            seen.add((nr, nc))
                            stack.append((nr, nc))
    return islands
