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

# Spiral Matrix

Given a matrix of\_m\_x\_n\_elements (\_m\_rows,\_n\_columns), return all elements of the matrix in spiral order.

**Example 1:**

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

**Example 2:**

```
Input:
[
  [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]
```

## Solution

```
class Solution {

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix.length == 0) {
            return result;
        }
        int firstRow = 0;
        int lastRow = matrix.length - 1;
        int leftColumn = 0; 
        int rightColumn = matrix[0].length - 1;

        while (firstRow <= lastRow && leftColumn <= rightColumn) {
            // read first row
            for (int i = leftColumn; i <= rightColumn; i++) {
                result.add(matrix[firstRow][i]);
            }

            // read right column
            for (int i = firstRow + 1; i <= lastRow; i++) {
                result.add(matrix[i][rightColumn]);
            }
            // to avoid duplicates (reading it backwards)
            if (firstRow < lastRow && leftColumn < rightColumn) {
                // read last row
                for (int i = rightColumn - 1; i >= leftColumn; i--) {
                    result.add(matrix[lastRow][i]);
                }

                // read left column
                for (int i = lastRow - 1; i > firstRow; i--) {
                    result.add(matrix[i][leftColumn]);
                }
            }

            firstRow++; // move first row down
            rightColumn--; // move right column to left
            lastRow--; // move last row up
            leftColumn++; // move left column to right

        }

        return result;
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://ondrej-kvasnovsky-2.gitbook.io/algorithms/interviews/google-leetcode/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.
