"""Stage 12: Graphs (problems 101-112)."""
from __future__ import annotations

from collections import defaultdict, deque
from typing import Dict, List, Optional

from .structures import GraphNode

DIRS = ((1, 0), (-1, 0), (0, 1), (0, -1))


def num_islands(grid: List[List[str]]) -> int:
    """LC 200. Each unvisited '1' starts a flood fill that sinks the whole island."""
    rows, cols = len(grid), len(grid[0])
    grid = [row[:] for row in grid]
    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != "1":
                continue
            count += 1
            stack = [(r, c)]
            grid[r][c] = "0"
            while stack:
                cr, cc = stack.pop()
                for dr, dc in DIRS:
                    nr, nc = cr + dr, cc + dc
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1":
                        grid[nr][nc] = "0"
                        stack.append((nr, nc))
    return count


def max_area_of_island(grid: List[List[int]]) -> int:
    """LC 695. Same flood fill, but count the cells."""
    rows, cols = len(grid), len(grid[0])
    seen = set()
    best = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != 1 or (r, c) in seen:
                continue
            seen.add((r, c))
            stack, area = [(r, c)], 0
            while stack:
                cr, cc = stack.pop()
                area += 1
                for dr, dc in DIRS:
                    nr, nc = cr + dr, cc + dc
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1 and (nr, nc) not in seen:
                        seen.add((nr, nc))
                        stack.append((nr, nc))
            best = max(best, area)
    return best


def clone_graph(node: Optional[GraphNode]) -> Optional[GraphNode]:
    """LC 133. old -> new map doubles as the visited set."""
    if not node:
        return None
    clones: Dict[GraphNode, GraphNode] = {node: GraphNode(node.val)}
    queue = deque([node])
    while queue:
        cur = queue.popleft()
        for nb in cur.neighbors:
            if nb not in clones:
                clones[nb] = GraphNode(nb.val)
                queue.append(nb)
            clones[cur].neighbors.append(clones[nb])
    return clones[node]


def oranges_rotting(grid: List[List[int]]) -> int:
    """LC 994. Multi-source BFS from every rotten orange; minutes = BFS layers."""
    rows, cols = len(grid), len(grid[0])
    grid = [row[:] for row in grid]
    queue = deque((r, c) for r in range(rows) for c in range(cols) if grid[r][c] == 2)
    fresh = sum(row.count(1) for row in grid)
    minutes = 0
    while queue and fresh:
        minutes += 1
        for _ in range(len(queue)):
            r, c = queue.popleft()
            for dr, dc in DIRS:
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
                    grid[nr][nc] = 2
                    fresh -= 1
                    queue.append((nr, nc))
    return -1 if fresh else minutes


def pacific_atlantic(heights: List[List[int]]) -> List[List[int]]:
    """LC 417. Reverse the flow: climb uphill from each ocean's border, intersect the two sets."""
    rows, cols = len(heights), len(heights[0])

    def reach(starts):
        seen = set(starts)
        stack = list(starts)
        while stack:
            r, c = stack.pop()
            for dr, dc in DIRS:
                nr, nc = r + dr, c + dc
                if (0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in seen
                        and heights[nr][nc] >= heights[r][c]):
                    seen.add((nr, nc))
                    stack.append((nr, nc))
        return seen

    pacific = reach([(0, c) for c in range(cols)] + [(r, 0) for r in range(rows)])
    atlantic = reach([(rows - 1, c) for c in range(cols)] + [(r, cols - 1) for r in range(rows)])
    return sorted([r, c] for r, c in pacific & atlantic)


def solve_surrounded(board: List[List[str]]) -> None:
    """LC 130. Mark 'O's connected to the border as safe; flip the rest to 'X'."""
    if not board:
        return
    rows, cols = len(board), len(board[0])
    stack = [(r, c) for r in range(rows) for c in (0, cols - 1)] + [(r, c) for r in (0, rows - 1) for c in range(cols)]
    while stack:
        r, c = stack.pop()
        if 0 <= r < rows and 0 <= c < cols and board[r][c] == "O":
            board[r][c] = "S"
            stack.extend((r + dr, c + dc) for dr, dc in DIRS)
    for r in range(rows):
        for c in range(cols):
            board[r][c] = "O" if board[r][c] == "S" else "X"


def _topo_order(num_courses: int, prerequisites: List[List[int]]) -> List[int]:
    graph = defaultdict(list)
    indegree = [0] * num_courses
    for course, pre in prerequisites:
        graph[pre].append(course)
        indegree[course] += 1
    queue = deque(i for i in range(num_courses) if indegree[i] == 0)
    order = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for nxt in graph[node]:
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                queue.append(nxt)
    return order


def can_finish(num_courses: int, prerequisites: List[List[int]]) -> bool:
    """LC 207. Kahn's algorithm: a cycle leaves some nodes with indegree > 0 forever."""
    return len(_topo_order(num_courses, prerequisites)) == num_courses


def find_order(num_courses: int, prerequisites: List[List[int]]) -> List[int]:
    """LC 210. The order Kahn's algorithm dequeues nodes is a valid course order."""
    order = _topo_order(num_courses, prerequisites)
    return order if len(order) == num_courses else []


def find_redundant_connection(edges: List[List[int]]) -> List[int]:
    """LC 684. Union-find: the first edge whose endpoints already share a root closes the cycle."""
    parent = list(range(len(edges) + 1))

    def root(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    for a, b in edges:
        ra, rb = root(a), root(b)
        if ra == rb:
            return [a, b]
        parent[ra] = rb
    return []


def ladder_length(begin: str, end: str, word_list: List[str]) -> int:
    """LC 127. BFS over words; wildcard patterns like 'h*t' connect neighbours in O(L) per word."""
    words = set(word_list)
    if end not in words:
        return 0
    patterns = defaultdict(list)
    for w in words | {begin}:
        for i in range(len(w)):
            patterns[w[:i] + "*" + w[i + 1:]].append(w)
    queue = deque([(begin, 1)])
    seen = {begin}
    while queue:
        word, steps = queue.popleft()
        if word == end:
            return steps
        for i in range(len(word)):
            for nxt in patterns[word[:i] + "*" + word[i + 1:]]:
                if nxt not in seen:
                    seen.add(nxt)
                    queue.append((nxt, steps + 1))
    return 0


def find_circle_num(is_connected: List[List[int]]) -> int:
    """LC 547. Count connected components of an adjacency matrix with DFS."""
    n = len(is_connected)
    seen = [False] * n
    provinces = 0
    for i in range(n):
        if seen[i]:
            continue
        provinces += 1
        stack = [i]
        seen[i] = True
        while stack:
            cur = stack.pop()
            for j in range(n):
                if is_connected[cur][j] and not seen[j]:
                    seen[j] = True
                    stack.append(j)
    return provinces


def is_bipartite(graph: List[List[int]]) -> bool:
    """LC 785. Two-colour each component with BFS; an edge inside one colour fails."""
    color = [-1] * len(graph)
    for start in range(len(graph)):
        if color[start] != -1:
            continue
        color[start] = 0
        queue = deque([start])
        while queue:
            node = queue.popleft()
            for nb in graph[node]:
                if color[nb] == -1:
                    color[nb] = 1 - color[node]
                    queue.append(nb)
                elif color[nb] == color[node]:
                    return False
    return True
