# leetcode – spiral matrix
Date: 2023-07-30


#### **问题：**

Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.**Input:**

```
array = [[1, 2, 3, 4], 
         [5, 6, 7, 8], 
         [9, 10, 11, 12],
         [13, 14, 15, 16 ]
        ]
```

**Output:**

\[1,2,3,4,8,12,11,10,9,5,6,7\]

#### **解答:**

1. 首先确定行列的边界值， startRow，endRow，startCol，endCol
2. 按照题目的要求进行螺旋便利 ， 分别向右， 向下， 向左， 向上移动，对应四个循环。
3. 特殊情况检查， 当出现单行或者单列的情况，在向左或向上遍历前， 分别检查行或列的边界值是否相等， startRow == endRow 或 startCol == endCol ， 相等则停止遍历。

```
def spiralTraverse(array):
    # Write your code here.
    result = []
    startRow , endRow = 0, len(array) - 1
    startCol, endCol = 0, len(array[0]) - 1

    while startRow <= endRow and startCol <= endCol:
        # right col 
        for col in range(startCol, endCol + 1):
            result.append(array[startRow][col])

        # down row
        for row in range(startRow + 1, endRow + 1):
            result.append(array[row][endCol])

        # left  col reversed
        for col in reversed(range(startCol, endCol)):
            if startRow == endRow:
                break;
            result.append(array[endRow][col])

        # up   row reversed
        for row in reversed(range(startRow+1, endRow)):
            if startCol == endCol:
                break;
            result.append(array[row][startCol])
        
        startRow = startRow + 1
        endRow = endRow -1
        startCol = startCol + 1
        endCol = endCol - 1

    return result
```

 

图片及引用

图片from[李進生](https://www.facebook.com/groups/296994820448873/user/100004783536637/?__cft__[0]=AZU1S_rwJ8bawqn1vHDlr-t_RUbxeL0oroBlLEPIacgaPzf5LH7Mz2kaiJGbme0Omt4fu2UJ2iSMU1csoh8h4xYninUWlIbLJlbVIjC7bGeN1riZ7lPlSzzUwHq1-pVTrP5UKgYOP5fvtd2oKKnhtjRysz-qEximNax_bVYkx-XyVLWVvuQN2qqcp4JO4ArocgM&__tn__=-UC*F)

https://www.algoexpert.io/questions/spiral-traverse

