sagelearnai

Matrix

Signal: a 2-D grid: rotate it, traverse it in a spiral or along diagonals, transform it in place, simulate cell updates, or search it with DFS/BFS.

Core ideas:

  • Index arithmetic: row r, column c; neighbors via direction arrays ((1,0), (-1,0), (0,1), (0,-1)).
  • Layer/boundary traversal: keep top, bottom, left, right bounds and shrink them (spiral order).
  • In-place tricks: reuse the first row/column as marker storage (Set Matrix Zeroes), or encode the old and new state in one value (Game of Life uses 2 bits).
  • Rotation = transpose + reverse: rotating 90° clockwise is transposing, then reversing each row.
python
# Spiral order with shrinking boundaries
def spiral(m):
    out, top, bot, left, right = [], 0, len(m) - 1, 0, len(m[0]) - 1
    while top <= bot and left <= right:
        out += [m[top][c] for c in range(left, right + 1)]; top += 1
        out += [m[r][right] for r in range(top, bot + 1)]; right -= 1
        if top <= bot:
            out += [m[bot][c] for c in range(right, left - 1, -1)]; bot -= 1
        if left <= right:
            out += [m[r][left] for r in range(bot, top - 1, -1)]; left += 1
    return out
Draw a 3×3 and a 3×4 example

Off-by-one errors in matrix problems hide in non-square shapes. Always test a rectangle and a single row or column.

Problems

  1. Set Matrix Zeroes (Medium): Use row 0 and column 0 as the marker arrays; one extra flag for column 0
  2. Spiral Matrix (Medium): Four shrinking boundaries: top, bottom, left, right
  3. Rotate Image (Medium): Transpose, then reverse each row (= 90° clockwise)
  4. Valid Sudoku (Medium): One pass with seen-sets per row, column and 3×3 box
  5. Game of Life (Medium): Encode next state in bit 1 while bit 0 keeps the current state; then shift
  6. Longest Increasing Path in a Matrix (Hard): DFS + memo: strictly increasing edges form a DAG, so no visited set is needed
  7. Transpose Matrix (Easy): result[c][r] = matrix[r][c]
  8. Matrix Diagonal Sum (Easy): Sum mat[i][i] + mat[i][n−1−i]; subtract the center once if n is odd
  9. Reshape the Matrix (Easy): Flat index k maps to (k // c, k % c)
  10. Spiral Matrix II (Medium): Same four boundaries, writing 1..n² instead of reading
  11. Diagonal Traverse (Medium): Group by d = r + c; reverse every even diagonal
  12. Plus One (Easy): Walk from the right: 9 → 0 and carry; otherwise +1 and stop