Skip to main content

⬜ Matrix

A matrix is a 2D array, but the geometry matters: rows, columns, diagonals, spirals, layers. Many matrix problems are graph problems in disguise (islands, walls-and-gates).

This category contains 18 problems. Use the patterns below to recognize what's being asked, then jump to the problem list at the bottom.


🧠 Key Patterns

  • Directional Arrays{dx, dy} = {{0,1},{1,0},{0,-1},{-1,0}} for 4-directional moves.
  • BFS / DFS on Grid — Connected components, flood fill, shortest path in maze.
  • In-place Marking — Use a sentinel value to mark visited without extra space.
  • Layer-by-layer Traversal — Spiral, rotate 90°.
  • Row/Column Independence — Set Matrix Zeroes — use first row/col as flags.
  • Diagonal Traversal — i+j (anti-diagonal) or i-j (diagonal) are constant.

⚠️ Common Pitfalls

  • Bound checks: a single missing < rows / < cols causes index errors that pass small tests.
  • In-place rotation: easy to overwrite values you still need — work with layer pairs.

📚 Study Resources

📺 Videos

📖 Books

  • Cracking the Coding Interview — Ch. 1 (Matrix problems mixed with Arrays)

🌐 Articles & References


💻 All Matrix Problems