🌀

Spiral Matrix Traversal

Intermediate

Learn spiral order matrix traversal through interactive challenges. Master boundary manipulation and spiral logic.

20-25 min
Level 1 - Easy

Spiral Matrix Traversal

Enter the spiral order of the matrix as a comma-separated list.

Matrix:

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

Enter Spiral Order:

Spiral Matrix Traversal - Algorithm

🎯 Problem Statement

Given a 2D matrix, return all elements of the matrix in spiral order (clockwise, starting from the top-left corner).

💡 Key Concepts

Boundary Tracking

Use four boundaries (top, bottom, left, right) to keep track of the current layer of the matrix.

Layer-by-Layer Traversal

Traverse the matrix in a spiral by moving right, down, left, and up, shrinking the boundaries after each direction.

📋 Algorithm Pseudo Code


function printSpiralMatrix(matrix):
    rMin = 0
    cMin = 0
    rMax = number of rows - 1
    cMax = number of columns - 1
    count = 0
    totalElements = number of rows * number of columns
    result = []
    while count < totalElements:
        # Traverse Top Boundary (left to right)
        for col from cMin to cMax and count < totalElements:
            result.append(matrix[rMin][col])
            count += 1
        rMin += 1
        # Traverse Right Boundary (top to bottom)
        for row from rMin to rMax and count < totalElements:
            result.append(matrix[row][cMax])
            count += 1
        cMax -= 1
        # Traverse Bottom Boundary (right to left)
        for col from cMax to cMin and count < totalElements:
            result.append(matrix[rMax][col])
            count += 1
        rMax -= 1
        # Traverse Left Boundary (bottom to top)
        for row from rMax to rMin and count < totalElements:
            result.append(matrix[row][cMin])
            count += 1
        cMin += 1
    return result

🔍 Step-by-Step Example

Input Matrix:

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

Spiral Order:

1, 2, 3, 6, 9, 8, 7, 4, 5

📊 Visual Representation

Original Matrix:
1
2
3
4
5
6
7
8
9
Spiral Order:
1, 2, 3, 6, 9, 8, 7, 4, 5

⏱️ Complexity Analysis

Time Complexity

O(m × n) - Each element is visited once.

Space Complexity

O(1) - If output is not counted as extra space.

🌍 Real-world Applications

🖼️Image processing (spiral scanning)
🧩Puzzle games and matrix-based board games
Progress1 / 3
Algorithm:Spiral Matrix Traversal
⌨️ Keyboard Navigation

Tab: Move to next input field

Enter: Check your answer

Numbers/Comma: Type directly to enter values

🎯 How to Play

1. Study the matrix shown on the left

2. Enter the spiral order as a comma-separated list

3. Click "Check Solution" to verify

4. Use Tab to move between fields

5. Click "Next Level" to try more

🔄 Algorithm Steps

Step 1: Traverse from left to right on the top row

Step 2: Traverse down the rightmost column

Step 3: Traverse from right to left on the bottom row

Step 4: Traverse up the leftmost column

Repeat for inner layers

📊 Level Info

Difficulty: Easy

Matrix Size: 3×3