Pattern #12

Matrix Traversal

Important interview questions, thinking patterns, 4-direction tricks, and rules for solving matrix traversal problems in Go.

Must Solve

16 core questions — solve these first.

  1. 1.Spiral Matrix
    medium
  2. 2.Rotate Image
    medium
  3. 3.Set Matrix Zeroes
    medium
  4. 4.Search a 2D Matrix
    medium
  5. 5.Search a 2D Matrix II
    medium
  6. 6.Diagonal Traverse
    medium
  7. 7.Reshape the Matrix
    easy
  8. 8.Transpose Matrix
    easy
  9. 9.Valid Sudoku
    medium
  10. 10.Game of Life
    medium
  11. 11.Flood Fill
    easy
  12. 12.Number of Islands
    medium
  13. 13.Surrounded Regions
    medium
  14. 14.Word Search
    medium
  15. 15.Max Area of Island
    medium
  16. 16.Pacific Atlantic Water Flow
    medium

Also Important

10 more questions worth practicing.

  1. 17.Matrix Diagonal Sum
    easy
  2. 18.Toeplitz Matrix
    easy
  3. 19.Richest Customer Wealth
    easy
  4. 20.Count Negative Numbers in a Sorted Matrix
    easy
  5. 21.Lucky Numbers in a Matrix
    easy
  6. 22.Rotate the Box
    medium
  7. 23.Spiral Matrix II
    medium
  8. 24.Battleships in a Board
    medium
  9. 25.Number of Closed Islands
    medium
  10. 26.Shortest Path in Binary Matrix
    medium

How to Think

  1. Need visit every cell?Rows × Columns → O(rows × cols)
  2. Need four directions?dirs := [][]int{{-1,0},{1,0},{0,-1},{0,1}}
  3. Need spiral?top, bottom, left, right (shrink boundaries)
  4. Need rotate matrix 90°?Transpose + Reverse Rows
  5. Need connected cells / islands?Grid DFS / BFS
  6. Need search sorted matrix?Binary Search or Top-Right Corner

Go Templates

Basic Nested Matrix Traversal

rows, cols := len(matrix), len(matrix[0])
for r := 0; r < rows; r++ {
    for c := 0; c < cols; c++ {
        val := matrix[r][c] // Choose row first, then column
        _ = val
    }
}

4-Directional Traversal Loop

dirs := [][]int{
    {-1, 0}, // Up
    {1, 0},  // Down
    {0, -1}, // Left
    {0, 1},  // Right
}

for _, d := range dirs {
    nr, nc := row+d[0], col+d[1]
    if nr >= 0 && nr < rows && nc >= 0 && nc < cols {
        // Valid neighboring cell inside bounds!
    }
}

Main Direction Trick & Rotate Transformation

Instead of writing 4 separate if-statements for Up, Down, Left, Right, use a direction array dirs:

dirs := [][]int{ {-1,0}, {1,0}, {0,-1}, {0,1} }

Rotate Matrix 90° Clockwise In-Place

1. Transpose: Swap matrix[i][j] with matrix[j][i]
2. Reverse Each Row: Reverse values in each row

Result: 90° Clockwise Rotation ✅
Visual Memory Rule
Spiral:  → top  ↓ right  ← bottom  ↑ left  (shrink boundaries)
Rotate:  Transpose + Reverse Rows
Dirs:    (-1,0), (1,0), (0,-1), (0,1)

💡 Golden Rule: "In matrix problems, always know: where am I, which direction can I move, and is the next cell valid?"

Common Interview Mistakes

1. Row / Column Confusion

Accidentally writing matrix[col][row] instead of matrix[row][col].

2. Out of Bounds Check Order

Check 0 <= nr < rows && 0 <= nc < cols BEFORE accessing matrix[nr][nc].

3. Infinite DFS Cycles

Forgetting a visited[r][c] set or mutating visited cells causes infinite recursion.

4. Assuming Square Matrix

Matrices can be non-square 3 x 5. Always use rows = len(matrix) and cols = len(matrix[0]).

Interview Rules

  1. 1. Visit every cell? → Rows × Columns
  2. 2. Four-direction movement? → Direction array dirs
  3. 3. Connected cells / Islands? → Grid DFS/BFS
  4. 4. Spiral? → 4 boundaries (top, bottom, left, right)
  5. 5. Rotate 90° clockwise? → Transpose + Reverse Rows
  6. 6. Sorted matrix? → Binary Search / Start from Top-Right corner
  7. 7. Avoid repeating visits? → Use visited matrix/set
  8. 8. Always check bounds before array lookup
  9. 9. Time complexity → usually O(rows × cols)
  10. 10. Don't assume square matrix (rows != cols)

Small Rules

  1. Rule 1: Always know both rows = len(matrix) and cols = len(matrix[0]).
  2. Rule 2: Check 0 <= newRow < rows && 0 <= newCol < cols before accessing cell.
  3. Rule 3: Nested loops over matrix are normal O(rows × cols), not bad complexity.
  4. Rule 4: Avoid visiting cells twice in grid DFS/BFS using a visited tracking mechanism.
  5. Rule 5: Be careful with non-square matrices where rows != cols.

Production Thinking

Image ProcessingPixels matrix (crop, rotate 90°, blur, edge detection)

Maps & Gaming GridsGrid BFS/DFS for pathfinding (0=free, 1=blocked)

Spreadsheet ProcessingRow x Column cell traversal & region aggregations

Seat Booking SystemsCinema/Airplane seat layout matrix (adjacent seat availability)

Game BoardsChess, Sudoku, Tic-Tac-Toe board state validation

Remember This

Every cell          → rows × cols
Neighbors           → direction array
Connected region    → DFS / BFS
Spiral              → top, right, bottom, left
Rotate 90°          → transpose + reverse
Sorted matrix       → binary search / corner search
Before moving       → bounds check
Visited before?     → skip

💡 Golden Rule: "In matrix problems, always know: where am I, which direction can I move, and is the next cell valid?"