> For the complete documentation index, see [llms.txt](https://jaywin.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jaywin.gitbook.io/leetcode/solutions/0054-spiral-matrix.md).

# 0054. Spiral Matrix

<https://leetcode.com/problems/spiral-matrix>

## Description

Given an `m x n` `matrix`, return *all elements of the* `matrix` *in spiral order*.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg)

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

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg)

```
**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`

## ac

```java
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<Integer>();
        if (matrix.length == 0) return res;
        int rb = 0, re = matrix.length-1;
        int cb = 0, ce = matrix[0].length - 1;
        while (rb <= re && cb <= ce) {
            // special cases
            if (rb == re){
                for (int c = cb; c <= ce; c++) res.add(matrix[rb][c]);
                break;
            }
            if (cb == ce) {
                for (int r = rb; r <= re; r++) res.add(matrix[r][ce]);
                break;
            }
            // top
            for (int c = cb; c < ce; c++) res.add(matrix[rb][c]);
            // right
            for (int r = rb; r < re; r++) res.add(matrix[r][ce]);
            // buttom
            for (int c = ce; c > cb; c--) res.add(matrix[re][c]);
            // left
            for (int r = re; r > cb; r--) res.add(matrix[r][cb]);
            // iterate
            rb++;
            re--;
            cb++;
            ce--;
        }
        return res;
    }
}
```
