Matrix Problems

Back

Loading concept...

πŸ—ΊοΈ Matrix Adventures: Navigating the Grid World

The Story of the Treasure Map

Imagine you have a big treasure map. But this isn’t just any mapβ€”it’s made of tiny squares arranged in rows and columns, like a checkerboard. Each square holds a secret number or clue. To find the treasure, you need to learn different ways to explore this grid!

In programming, we call this grid a Matrix. Think of it like:

  • A chocolate bar with rows and columns of pieces
  • A tic-tac-toe board
  • A seating chart in your classroom

Today, you’ll become a Matrix Explorer and learn 5 magical patterns to navigate any grid!


🚢 Matrix Traversal Patterns

What Is Traversal?

Traversal means visiting every square in the matrix. It’s like checking every seat in a movie theater to find your friend!

The Two Basic Ways

Row-by-Row (Left to Right)

// Like reading a book!
for(int i = 0; i < rows; i++) {
    for(int j = 0; j < cols; j++) {
        visit(matrix[i][j]);
    }
}

Column-by-Column (Top to Bottom)

// Like reading a tall list!
for(int j = 0; j < cols; j++) {
    for(int i = 0; i < rows; i++) {
        visit(matrix[i][j]);
    }
}

Simple Example

Matrix:
1  2  3
4  5  6
7  8  9

Row-by-Row: 1β†’2β†’3β†’4β†’5β†’6β†’7β†’8β†’9
Column-by-Column: 1β†’4β†’7β†’2β†’5β†’8β†’3β†’6β†’9

Real Life: Reading a bookshelfβ€”you can go shelf by shelf (rows) or book position by position (columns)!


πŸŒ€ Spiral Matrix: The Snail’s Journey

The Story

Imagine a snail starting at the top-left corner of a garden grid. It walks along the edge, turns right at corners, and slowly spirals inward until it reaches the center. That’s exactly how Spiral Matrix works!

graph TD A["Start: Top-Left"] --> B["Go Right along top"] B --> C["Go Down right side"] C --> D["Go Left along bottom"] D --> E["Go Up left side"] E --> F["Repeat inward"] F --> G["Reach Center"]

How It Works

  1. Walk Right β†’ across the top row
  2. Walk Down β†’ along the right column
  3. Walk Left β†’ across the bottom row
  4. Walk Up β†’ along the left column
  5. Shrink the boundary β†’ repeat for inner layers

Java Code

public List<Integer> spiralOrder(
    int[][] matrix) {

    List<Integer> result =
        new ArrayList<>();

    int top = 0;
    int bottom = matrix.length - 1;
    int left = 0;
    int right = matrix[0].length - 1;

    while(top <= bottom &&
          left <= right) {

        // Right β†’
        for(int i=left; i<=right; i++)
            result.add(matrix[top][i]);
        top++;

        // Down ↓
        for(int i=top; i<=bottom; i++)
            result.add(matrix[i][right]);
        right--;

        // Left ← (if rows remain)
        if(top <= bottom) {
            for(int i=right; i>=left; i--)
                result.add(matrix[bottom][i]);
            bottom--;
        }

        // Up ↑ (if cols remain)
        if(left <= right) {
            for(int i=bottom; i>=top; i--)
                result.add(matrix[i][left]);
            left++;
        }
    }
    return result;
}

Visual Example

Input:
1  2  3
4  5  6
7  8  9

Spiral Path:
1 β†’ 2 β†’ 3
        ↓
4 β†’ 5   6
↑       ↓
7 ← 8 ← 9

Output: [1,2,3,6,9,8,7,4,5]

πŸ”„ Rotate Matrix: The Dance Floor Spin

The Story

Imagine all dancers on a square dance floor. When the DJ shouts β€œROTATE!”, everyone spins 90Β° clockwise together. The person at top-left moves to top-right, top-right goes to bottom-right, and so on!

The Magic Two-Step Trick

Rotating 90Β° clockwise is actually super easy with two moves:

  1. Transpose β†’ Flip the matrix over its diagonal (rows become columns)
  2. Reverse each row β†’ Mirror each row horizontally
graph TD A["Original Matrix"] --> B["Step 1: Transpose"] B --> C["Step 2: Reverse Rows"] C --> D["90Β° Rotated!"]

Java Code

public void rotate(int[][] matrix) {
    int n = matrix.length;

    // Step 1: Transpose
    // Swap matrix[i][j] with matrix[j][i]
    for(int i = 0; i < n; i++) {
        for(int j = i; j < n; j++) {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;
        }
    }

    // Step 2: Reverse each row
    for(int i = 0; i < n; i++) {
        int left = 0, right = n - 1;
        while(left < right) {
            int temp = matrix[i][left];
            matrix[i][left] = matrix[i][right];
            matrix[i][right] = temp;
            left++;
            right--;
        }
    }
}

Visual Example

Original:     Transpose:    Reverse Rows:
1  2  3       1  4  7       7  4  1
4  5  6  β†’    2  5  8   β†’   8  5  2
7  8  9       3  6  9       9  6  3

Pro Tip: For counter-clockwise rotation, reverse rows FIRST, then transpose!


0️⃣ Set Matrix Zeroes: The Virus Spread

The Story

Imagine a classroom seating chart. If one student gets sick (marked as 0), everyone in their row AND column has to go home too (becomes 0). One sick student affects the whole row and column!

The Challenge

If we just scan and set zeroes immediately, we’ll create new zeroes that spread incorrectly. We need a marking phase first!

Smart Solution: Use First Row & Column as Markers

graph TD A["Find all original 0s"] --> B["Mark in first row/col"] B --> C["Set zeroes using marks"] C --> D["Handle first row/col last"]

Java Code

public void setZeroes(int[][] matrix) {
    int m = matrix.length;
    int n = matrix[0].length;

    boolean firstRowZero = false;
    boolean firstColZero = false;

    // Check if first row has zero
    for(int j = 0; j < n; j++) {
        if(matrix[0][j] == 0) {
            firstRowZero = true;
            break;
        }
    }

    // Check if first col has zero
    for(int i = 0; i < m; i++) {
        if(matrix[i][0] == 0) {
            firstColZero = true;
            break;
        }
    }

    // Use first row/col as markers
    for(int i = 1; i < m; i++) {
        for(int j = 1; j < n; j++) {
            if(matrix[i][j] == 0) {
                matrix[i][0] = 0;
                matrix[0][j] = 0;
            }
        }
    }

    // Set zeroes based on markers
    for(int i = 1; i < m; i++) {
        for(int j = 1; j < n; j++) {
            if(matrix[i][0] == 0 ||
               matrix[0][j] == 0) {
                matrix[i][j] = 0;
            }
        }
    }

    // Handle first row
    if(firstRowZero) {
        for(int j = 0; j < n; j++)
            matrix[0][j] = 0;
    }

    // Handle first column
    if(firstColZero) {
        for(int i = 0; i < m; i++)
            matrix[i][0] = 0;
    }
}

Visual Example

Input:         Mark:          Output:
1  1  1        1  1  0        1  1  0
1  0  1   β†’    0  0  1   β†’    0  0  0
1  1  1        1  1  1        0  1  0

The 0 at [1][1] "spreads" to its row and column!

πŸ” Search a 2D Matrix II: The Smart Library Search

The Story

Imagine a magical library where:

  • Books in each shelf are sorted left to right (small β†’ big)
  • Books on each stack are sorted top to bottom (small β†’ big)

To find a specific book number, you don’t need to check every book! Start from a magic corner and let the numbers guide you.

The Magic Corner Strategy

Start at top-right (or bottom-left). From there:

  • If target is smaller β†’ move LEFT (numbers get smaller)
  • If target is bigger β†’ move DOWN (numbers get bigger)
graph TD A["Start Top-Right"] --> B{Compare with target} B -->|Target smaller| C["Move Left"] B -->|Target bigger| D["Move Down"] B -->|Equal| E["Found it!"] C --> B D --> B

Java Code

public boolean searchMatrix(
    int[][] matrix, int target) {

    if(matrix == null ||
       matrix.length == 0) {
        return false;
    }

    int rows = matrix.length;
    int cols = matrix[0].length;

    // Start from top-right corner
    int row = 0;
    int col = cols - 1;

    while(row < rows && col >= 0) {
        int current = matrix[row][col];

        if(current == target) {
            return true;  // Found!
        }
        else if(current > target) {
            col--;  // Go left
        }
        else {
            row++;  // Go down
        }
    }

    return false;  // Not found
}

Visual Example

Matrix (sorted rows & cols):
1   4   7   11  15
2   5   8   12  19
3   6   9   16  22
10  13  14  17  24
18  21  23  26  30

Find: 5

Step 1: Start at 15 β†’ 5 < 15 β†’ go left
Step 2: At 11 β†’ 5 < 11 β†’ go left
Step 3: At 7 β†’ 5 < 7 β†’ go left
Step 4: At 4 β†’ 5 > 4 β†’ go down
Step 5: At 5 β†’ FOUND! βœ“

Only 5 steps instead of checking 25 cells!

🧠 Quick Comparison Chart

Problem Key Insight Time Complexity
Traversal Nested loops O(m Γ— n)
Spiral 4 boundaries + shrink O(m Γ— n)
Rotate Transpose + Reverse O(nΒ²)
Set Zeroes Mark first row/col O(m Γ— n)
Search 2D II Start from corner O(m + n)

🎯 Key Takeaways

  1. Matrix = Grid of boxes arranged in rows and columns
  2. Traversal = Visit every box systematically
  3. Spiral = Walk the edges, then shrink inward like a snail
  4. Rotate = Transpose + Reverse (the magic two-step!)
  5. Set Zeroes = Mark first, then spread (avoid chain reactions)
  6. Search 2D II = Start at magic corner, eliminate row OR column each step

You’re now a Matrix Master! These patterns appear everywhere in coding interviews and real applications. Practice each one, and soon navigating any grid will feel as natural as walking through your own neighborhood!


Remember: Every complex matrix problem is just a combination of these simple patterns. Break it down, think step by step, and you’ve got this! πŸš€

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.