⬜ 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/< colscauses 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
1 Matrix
LeetCode 542 | Difficulty: Medium
Battleships in a Board
LeetCode 419 | Difficulty: Medium
Diagonal Traverse
LeetCode 498 | Difficulty: Medium
Island Perimeter
LeetCode 463 | Difficulty: Easy
Longest Increasing Path in a Matrix
LeetCode 329 | Difficulty: Hard
Matrix Diagonal Sum
LeetCode 1677 | Difficulty: Easy
Reshape the Matrix
LeetCode 566 | Difficulty: Easy
Rotate Image
LeetCode 48 | Difficulty: Medium
Search a 2D Matrix
LeetCode 74 | Difficulty: Medium
Search a 2D Matrix II
LeetCode 240 | Difficulty: Medium
Set Matrix Zeroes
LeetCode 73 | Difficulty: Medium
Spiral Matrix
LeetCode 54 | Difficulty: Medium
Spiral Matrix II
LeetCode 59 | Difficulty: Medium
Sudoku Solver
LeetCode 37 | Difficulty: Hard
Toeplitz Matrix
LeetCode 777 | Difficulty: Easy
Transpose Matrix
LeetCode 898 | Difficulty: Easy
Valid Sudoku
LeetCode 36 | Difficulty: Medium
Walls and Gates
LeetCode Link