Python Spiral Matrix Traversal

Traverse and list the elements of a 2D matrix in spiral order in Python.

Try Python Spiral Matrix Traversal Code

How it Works

Spiral matrix traversal is a classic multidimensional array problem. It requires traversing the outer borders clockwise and progressively shrinking the boundaries.

We maintain four pointers: `top`, `bottom`, `left`, and `right` to track the bounds of the unvisited matrix parts.

By traversing from left to right, top to bottom, right to left, and bottom to top in sequence, we cover all cells systematically.

Source Code

Clockwise spiral traversal showing index manipulation.

spiral.py
Try in Editor
def spiral_order(matrix):
    if not matrix:
        return []
        
    result = []
    top, bottom = 0, len(matrix) - 1
    left, right = 0, len(matrix[0]) - 1
    
    while top <= bottom and left <= right:
        # Traverse Right
        for col in range(left, right + 1):
            result.append(matrix[top][col])
        top += 1
        
        # Traverse Down
        for row in range(top, bottom + 1):
            result.append(matrix[row][right])
        right -= 1
        
        if top <= bottom:
            # Traverse Left
            for col in range(right, left - 1, -1):
                result.append(matrix[bottom][col])
            bottom -= 1
            
        if left <= right:
            # Traverse Up
            for row in range(bottom, top - 1, -1):
                result.append(matrix[row][left])
            left += 1
            
    return result

grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print("Matrix Spiral Order:")
print(spiral_order(grid))
Terminal Output
Matrix Spiral Order:
[1, 2, 3, 6, 9, 8, 7, 4, 5]

Real-world Applications

  • 2D graphics rendering and spiral path tracking
  • Grid layout navigation patterns in data engines
  • Advanced algorithm assessment tests

Frequently Asked Questions

What is the time complexity of spiral traversal?

The time complexity is O(m * n) where m is rows and n is columns, because we visit every cell in the grid exactly once.

More Examples