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, rightbounds 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 outDraw 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.