"""Blind 75, Matrix section (4 problems)."""
from typing import List


def set_zeroes(matrix: List[List[int]]) -> None:
    """LC 73. O(1) space: use the first row and column as marker arrays, with one flag for row 0 itself."""
    rows, cols = len(matrix), len(matrix[0])
    first_row_zero = any(v == 0 for v in matrix[0])
    for r in range(1, rows):
        for c in range(cols):
            if matrix[r][c] == 0:
                matrix[r][0] = 0
                matrix[0][c] = 0
    for r in range(1, rows):
        for c in range(1, cols):
            if matrix[r][0] == 0 or matrix[0][c] == 0:
                matrix[r][c] = 0
    if matrix[0][0] == 0:
        for r in range(rows):
            matrix[r][0] = 0
    if first_row_zero:
        for c in range(cols):
            matrix[0][c] = 0


def spiral_order(matrix: List[List[int]]) -> List[int]:
    """LC 54. Shrink four boundaries (top, bottom, left, right) after walking each edge."""
    out: List[int] = []
    top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1
    while top <= bottom and left <= right:
        out += matrix[top][left:right + 1]
        top += 1
        out += [matrix[r][right] for r in range(top, bottom + 1)]
        right -= 1
        if top <= bottom:
            out += matrix[bottom][left:right + 1][::-1]
            bottom -= 1
        if left <= right:
            out += [matrix[r][left] for r in range(bottom, top - 1, -1)]
            left += 1
    return out


def rotate(matrix: List[List[int]]) -> None:
    """LC 48. Rotate 90 degrees clockwise = transpose, then reverse each row. In place."""
    n = len(matrix)
    for r in range(n):
        for c in range(r + 1, n):
            matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
    for row in matrix:
        row.reverse()


def exist(board: List[List[str]], word: str) -> bool:
    """LC 79. Backtracking DFS from every cell; mark the cell as used, then restore it on the way back."""
    rows, cols = len(board), len(board[0])

    def dfs(r: int, c: int, i: int) -> bool:
        if i == len(word):
            return True
        if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[i]:
            return False
        board[r][c] = "#"
        found = any(dfs(r + dr, c + dc, i + 1) for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)))
        board[r][c] = word[i]
        return found

    return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))
