Grids & Matrices
Grids & Matrices problems usually involve traversing a 2D board and maintaining visited state.
KEY TAKEAWAYS
- Directions Array: Use an array of offsets (e.g.,
[[0, 1], [1, 0], ...]) to simplify navigating neighbors in a grid. - Boundary Checks: Always validate indices before accessing grid cells. A helper function like
is_valid(r, c)keeps code clean. - Matrix Traversal: Be comfortable iterating through grids in various orders: row-by-row, column-by-column, backwards, or in spirals.
- 2D Prefix Sums: For subgrid sum queries, use the inclusion-exclusion principle (add sides, subtract overlap).
- Matrix Transformations: Transposing swaps rows and columns (
[r][c] -> [c][r]). Rotating involves mapping[r][c]to transformed coordinates (e.g.,[c][n-1-r]).
Practice Problems
Number of Islands
Practice this problem with interactive visualization.
Flood Fill
Practice this problem with interactive visualization.
Rotting Oranges
Practice this problem with interactive visualization.
Chess Moves
Practice this problem with interactive visualization.
Queens That Can Attack the King
Practice this problem with interactive visualization.
Spiral Matrix
Practice this problem with interactive visualization.
Spiral Matrix II
Practice this problem with interactive visualization.
Beyond Cracking the Coding Interview
Snowprints
Practice this problem with interactive visualization.
Spiral Order (From Center)
Practice this problem with interactive visualization.
Valid Sudoku
Practice this problem with interactive visualization.
Subgrid Maximums
Practice this problem with interactive visualization.
Subgrid Sums
Practice this problem with interactive visualization.
Matrix Operations (Rotate & In-place)
Practice this problem with interactive visualization.