---
title: '54. Spiral Matrix'
description: Given an m x n matrix, return all elements of the matrix in spiral order
sidebar:
  label: 'Spiral Matrix'
  badge: 'Medium'
---

Array

### Example 1:
- Input: `matrix = [[1,2,3],[4,5,6],[7,8,9]]`
- Output: `[1,2,3,6,9,8,7,4,5]`

### Example 2:
- Input: `matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]`
- Output: `[1,2,3,4,8,12,11,10,9,5,6,7]`

### Constraints:

- `m == matrix.length`
- `n == matrix[i].length`
- `1 <= m, n <= 10`
- `-100 <= matrix[i][j] <= 100`

## Approach

```mermaid
flowchart TD
  S(["spiralOrder(matrix)"]) --> I["res = [], top = 0, bottom = len(matrix) - 1, left = 0, right = len(matrix[0]) - 1"]
  I --> W{"top <= bottom and left <= right?"}
  W -- no --> E(["return res"])
  W -- yes --> T["append matrix[top][c] for c in left..right, then top += 1 — top row, shrink from above"]
  T --> R["append matrix[r][right] for r in top..bottom, then right -= 1 — right column"]
  R --> B{"top <= bottom?"}
  B -- yes --> C["append matrix[bottom][c] for c in right down to left, then bottom -= 1 — bottom row"]
  C --> L{"left <= right?"}
  B -- no --> L
  L -- yes --> D["append matrix[r][left] for r in bottom down to top, then left += 1 — left column"]
  D --> W
  L -- no --> W
```

## Solution

```py
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        top, bottom = 0, len(matrix) - 1
        left, right = 0, len(matrix[0]) - 1

        while top <= bottom and left <= right:
            # 1. Top Row
            for c in range(left, right + 1):
                res.append(matrix[top][c])
            top += 1

            # 2. Right Column
            for r in range(top, bottom + 1):
                res.append(matrix[r][right])
            right -= 1

            # 3. Bottom Row
            if top <= bottom:
                for c in range(right, left - 1, -1):
                    res.append(matrix[bottom][c])
                bottom -= 1

            # 4. Left Column
            if left <= right:
                for r in range(bottom, top - 1, -1):
                    res.append(matrix[r][left])
                left += 1

        return res
```

## Explanation

[Spiral Matrix - Microsoft Interview Question - Leetcode 54](https://www.youtube.com/watch?v=BJnMZNwUk1M)
