# LeetCode 54: Spiral Matrix — Step-by-Step Visual Trace

**Medium** — Array | Matrix | Simulation | Traversal

## The Problem

Given an m x n matrix, return all elements of the matrix in spiral order, starting from the top-left corner and moving clockwise through each layer.

## Approach

Use four boundary variables (top, bottom, left, right) to define the current layer being traversed. Move clockwise by traversing top row, right column, bottom row, and left column, then shrink boundaries inward for the next layer.

**Time:** O(m * n) · **Space:** O(1)

## Code

```python
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return []

        rows, cols = len(matrix), len(matrix[0])
        result = []

        # Define the boundaries of the current layer
        top, bottom, left, right = 0, rows - 1, 0, cols - 1

        while top <= bottom and left <= right:
            # Traverse the top row
            for j in range(left, right + 1):
                result.append(matrix[top][j])
            top += 1

            # Traverse the right column
            for i in range(top, bottom + 1):
                result.append(matrix[i][right])
            right -= 1

            # Traverse the bottom row
            if top <= bottom:  # Avoid duplicate traversal
                for j in range(right, left - 1, -1):
                    result.append(matrix[bottom][j])
                bottom -= 1

            # Traverse the left column
            if left <= right:  # Avoid duplicate traversal
                for i in range(bottom, top - 1, -1):
                    result.append(matrix[i][left])
                left += 1

        return result
```

## Watch It Run

> **[Open interactive visualization](https://tracelit.dev/app?trace=0054_spiral-matrix)**

> **Try it yourself:** Open [TraceLit](https://tracelit.dev/app?trace=0054_spiral-matrix) and step through every line.

---

*Built with [TraceLit](https://tracelit.dev) — the visual algorithm tracer for LeetCode practice.*
