# 23. \[matrix] Spiral Matrix

54\. Spiral MatrixMedium12.5K1.1KCompanies

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)

<pre><code><strong>Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
</strong><strong>Output: [1,2,3,6,9,8,7,4,5]
</strong></code></pre>

**Example 2:**

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

<pre><code><strong>Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
</strong><strong>Output: [1,2,3,4,8,12,11,10,9,5,6,7]
</strong></code></pre>

**Constraints:**

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

{% embed url="<https://leetcode.com/problems/spiral-matrix/description/>" %}

```javascript
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (m) {

    let w = m[0].length;
    let h = m.length - 1;

    const answer = [];
    let row = 0;
    let col = -1;
    while (w >= 0 && h >= 0) {
        col++;
        for (let i = 0; i < w; i++) {
            const curr = m[row][col];
            answer.push(curr);
            col++;
        }
        w--;
        if (w < 0) break;
        col--;

        row++;
        for (let i = 0; i < h; i++) {
            const curr = m[row][col];
            answer.push(curr);
            row++;
        }
        h--;
        if (h < 0) break;
        row--;

        col--;
        for (let i = 0; i < w; i++) {
            const curr = m[row][col];
            answer.push(curr);
            col--;
        }
        w--;
        if (w < 0) break;
        col++;

        row--;
        for (let i = 0; i < h; i++) {
            const curr = m[row][col];
            answer.push(curr);
            row--;
        }
        h--;
        if (h < 0) break;
        row++;
    }


    return answer;
};
```
