> For the complete documentation index, see [llms.txt](https://liuxue2010.gitbook.io/data-structure-and-algorithms/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://liuxue2010.gitbook.io/data-structure-and-algorithms/array-and-numbers/spiral-matrix.md).

# Spiral Matrix

Given a matrix ofmxnelements (mrows,ncolumns), return all elements of the matrix in spiral order.

For example,\
Given the following matrix:

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

You should return

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

.**Solution**

这道题需要一个对角线的起始，结束的行列指针，我一开始犯的错误就是直接使用了running number 。

```
class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if matrix == None or len(matrix) == 0:
            return []
        if matrix[0] == None or len(matrix[0]) == 0:
            return []
        m = len(matrix)
        n = len(matrix[0])
        result = []

        c, r = 0, 0

        while r < m and c < n:
            for i in range(c, n):
                result.append(matrix[r][i])
            r += 1
            for i in range(r, m):
                result.append(matrix[i][n - 1])
            n -= 1
            if r < m:
                for i in range(n - 1, c - 1, -1):
                    result.append(matrix[m - 1][i])
                m -= 1
            if c < n:
                for i in range(m - 1, r - 1, -1):
                    result.append(matrix[i][c])
                c += 1
        return result
```
