# 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;
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/daily-algorithms/23.-matrix-spiral-matrix.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
