0
0
DSA Pythonprogramming

Spiral Matrix Traversal in DSA Python

Choose your learning style9 modes available
Mental Model
We walk around the edges of the matrix in a circle, then move inward layer by layer until all elements are visited.
Analogy: Imagine peeling an onion layer by layer, starting from the outer skin and moving towards the center, collecting all the layers as you go.
1 -> 2 -> 3 -> 4
↓           ↑
5           6
↓           ↑
7 ← 8 ← 9 ← 10

We start at top-left, move right, then down, then left, then up, shrinking the boundaries each time.
Dry Run Walkthrough
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Goal: Traverse the matrix in spiral order and collect elements in that sequence.
Step 1: Traverse top row from left to right
Visited: 1 -> 2 -> 3
Remaining matrix edges to traverse
Why: Start from the top row to begin the outer layer traversal
Step 2: Traverse right column from top to bottom (excluding already visited top row)
Visited: 1 -> 2 -> 3 -> 6 -> 9
Remaining edges: bottom row and left column
Why: Move down the right edge to continue the spiral
Step 3: Traverse bottom row from right to left (excluding already visited right column)
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7
Remaining edge: left column
Why: Move left along the bottom edge to complete the outer layer
Step 4: Traverse left column from bottom to top (excluding already visited bottom and top rows)
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4
Remaining center element
Why: Move up the left edge to finish the outer layer
Step 5: Move inward and traverse the remaining center element
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Why: All outer layers done, now visit the center
Result:
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Annotated Code
DSA Python
from typing import List

class SpiralMatrix:
    def spiral_order(self, matrix: List[List[int]]) -> List[int]:
        result = []
        if not matrix or not matrix[0]:
            return result

        top, bottom = 0, len(matrix) - 1
        left, right = 0, len(matrix[0]) - 1

        while left <= right and top <= bottom:
            # Traverse from left to right on the top row
            for col in range(left, right + 1):
                result.append(matrix[top][col])
            top += 1  # move top boundary down

            # Traverse from top to bottom on the right column
            for row in range(top, bottom + 1):
                result.append(matrix[row][right])
            right -= 1  # move right boundary left

            if top <= bottom:
                # Traverse from right to left on the bottom row
                for col in range(right, left - 1, -1):
                    result.append(matrix[bottom][col])
                bottom -= 1  # move bottom boundary up

            if left <= right:
                # Traverse from bottom to top on the left column
                for row in range(bottom, top - 1, -1):
                    result.append(matrix[row][left])
                left += 1  # move left boundary right

        return result

if __name__ == "__main__":
    matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
    spiral = SpiralMatrix()
    result = spiral.spiral_order(matrix)
    print(" -> ".join(map(str, result)))
while left <= right and top <= bottom:
continue spiral traversal while boundaries are valid
for col in range(left, right + 1): result.append(matrix[top][col])
traverse top row from left to right
top += 1
shrink top boundary down after traversal
for row in range(top, bottom + 1): result.append(matrix[row][right])
traverse right column from top to bottom
right -= 1
shrink right boundary left after traversal
if top <= bottom: for col in range(right, left - 1, -1): result.append(matrix[bottom][col])
traverse bottom row from right to left if still valid
bottom -= 1
shrink bottom boundary up after traversal
if left <= right: for row in range(bottom, top - 1, -1): result.append(matrix[row][left])
traverse left column from bottom to top if still valid
left += 1
shrink left boundary right after traversal
OutputSuccess
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Complexity Analysis
Time: O(m*n) because every element in the m by n matrix is visited exactly once
Space: O(m*n) for the output list that stores all elements of the matrix
vs Alternative: Compared to naive repeated scanning, this approach visits each element once without revisiting, making it efficient
Edge Cases
Empty matrix
Returns empty list immediately
DSA Python
if not matrix or not matrix[0]:
    return result
Single row matrix
Traverses left to right only
DSA Python
while left <= right and top <= bottom:
Single column matrix
Traverses top to bottom only
DSA Python
while left <= right and top <= bottom:
When to Use This Pattern
When you need to visit all elements of a matrix in a circular, inward pattern, use spiral traversal to systematically peel layers.
Common Mistakes
Mistake: Not updating boundaries correctly causing infinite loops or repeated elements
Fix: After each edge traversal, update the corresponding boundary (top, bottom, left, right) to move inward
Mistake: Not checking boundary conditions before traversing bottom row or left column
Fix: Add checks like if top <= bottom and if left <= right before those traversals
Summary
It collects matrix elements in a spiral order starting from the outer layer moving inward.
Use it when you want to read or print matrix elements in a circular pattern.
The key is to keep track of four boundaries and move them inward after each edge traversal.