"""Blind 75, Graph section (8 problems)."""
from collections import defaultdict, deque
from typing import Dict, List, Optional

from .structures import GraphNode


def clone_graph(node: Optional[GraphNode]) -> Optional[GraphNode]:
    """LC 133. DFS with an old->new map; the map doubles as the visited set and handles cycles."""
    copies: Dict[GraphNode, GraphNode] = {}

    def copy(n: GraphNode) -> GraphNode:
        if n in copies:
            return copies[n]
        c = copies[n] = GraphNode(n.val)
        c.neighbors = [copy(x) for x in n.neighbors]
        return c

    return copy(node) if node else None


def can_finish(num_courses: int, prerequisites: List[List[int]]) -> bool:
    """LC 207. Kahn's topological sort: if every course gets in-degree 0 at some point, there is no cycle."""
    graph = defaultdict(list)
    indeg = [0] * num_courses
    for course, pre in prerequisites:
        graph[pre].append(course)
        indeg[course] += 1
    queue = deque(i for i in range(num_courses) if indeg[i] == 0)
    taken = 0
    while queue:
        c = queue.popleft()
        taken += 1
        for nxt in graph[c]:
            indeg[nxt] -= 1
            if indeg[nxt] == 0:
                queue.append(nxt)
    return taken == num_courses


def pacific_atlantic(heights: List[List[int]]) -> List[List[int]]:
    """LC 417. Flip the direction: flood uphill from each ocean's border, answer is the intersection."""
    rows, cols = len(heights), len(heights[0])

    def flood(starts):
        seen = set(starts)
        stack = list(starts)
        while stack:
            r, c = stack.pop()
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                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 = flood([(0, c) for c in range(cols)] + [(r, 0) for r in range(rows)])
    atlantic = flood([(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 num_islands(grid: List[List[str]]) -> int:
    """LC 200. Each unvisited '1' starts a new island; sink it with DFS so it is counted once."""
    grid = [row[:] for row in grid]
    rows, cols = len(grid), len(grid[0])
    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:
                y, x = stack.pop()
                for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
                    if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == "1":
                        grid[ny][nx] = "0"
                        stack.append((ny, nx))
    return count


def longest_consecutive(nums: List[int]) -> int:
    """LC 128. Only start counting at n when n-1 is absent; each run is walked once, so O(n)."""
    values = set(nums)
    best = 0
    for n in values:
        if n - 1 not in values:
            length = 1
            while n + length in values:
                length += 1
            best = max(best, length)
    return best


def alien_order(words: List[str]) -> str:
    """LC 269 (Premium). First differing letter of adjacent words gives an edge; topo-sort the letters.
    A word followed by its own proper prefix is invalid, so return ""."""
    graph: Dict[str, set] = {ch: set() for w in words for ch in w}
    for a, b in zip(words, words[1:]):
        for x, y in zip(a, b):
            if x != y:
                graph[x].add(y)
                break
        else:
            if len(a) > len(b):
                return ""
    indeg = {ch: 0 for ch in graph}
    for ch in graph:
        for nxt in graph[ch]:
            indeg[nxt] += 1
    queue = deque(sorted(ch for ch in graph if indeg[ch] == 0))
    order = []
    while queue:
        ch = queue.popleft()
        order.append(ch)
        for nxt in sorted(graph[ch]):
            indeg[nxt] -= 1
            if indeg[nxt] == 0:
                queue.append(nxt)
    return "".join(order) if len(order) == len(graph) else ""


class _DSU:
    def __init__(self, n: int):
        self.parent = list(range(n))

    def find(self, x: int) -> int:
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x

    def union(self, a: int, b: int) -> bool:
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        self.parent[ra] = rb
        return True


def valid_tree(n: int, edges: List[List[int]]) -> bool:
    """LC 261 (Premium). A tree has exactly n-1 edges and no cycle; union-find detects the cycle."""
    if len(edges) != n - 1:
        return False
    dsu = _DSU(n)
    return all(dsu.union(a, b) for a, b in edges)


def count_components(n: int, edges: List[List[int]]) -> int:
    """LC 323 (Premium). Start with n components; every successful union merges two into one."""
    dsu = _DSU(n)
    return n - sum(dsu.union(a, b) for a, b in edges)
