###### tags: `Leetcode` `medium` `array` `python` `Top 100 Liked Questions` # 54. Spiral Matrix ## [題目連結:] https://leetcode.com/problems/spiral-matrix/ ## 題目: Given an ```m x n matrix```, return all elements of the ```matrix``` in spiral order. ![](https://i.imgur.com/iI08Gb3.png) ![](https://i.imgur.com/onUMWYt.png) #### [圖片連結] https://leetcode.com/problems/spiral-matrix/ ## 解題想法: * 按照順序輸出 * 固定好邊界 * 上邊: top=0 * 下邊: bottom=len(matrix)-1 * 左邊: left=0 * 右邊: right=len(matrix[0])-1 * 依序輸出: * 最上層(由左到右)->右邊(由上到下、且不含角落)->最下層(由右到左)->左邊(由下到上、且不含角落) ## Python: ``` python= class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ top = 0 #上邊 bottom = len(matrix)-1 #下邊 left = 0 #左邊 right = len(matrix[0])-1 #右邊 ans = [] while top<bottom and left<right: #輸出最上層 #range為左右寬 ans += matrix[top][left:right+1] #輸出最右邊一列: 不含右上右下角,從top+1開始 #range為上下長 for i in range(top+1,bottom): ans.append(matrix[i][right]) #輸出最下層 ans += matrix[bottom][left:right+1][::-1] #輸出最左層 (不含左上左下角) for i in range(bottom-1,top,-1): ans.append(matrix[i][left]) top +=1 bottom -=1 left +=1 right -=1 #若剩下最後一列 if top==bottom: ans+=matrix[top][left:right+1] #若剩下最後一行 elif left==right: #注意!! 不用管角落,正常遍歷 for i in range(top,bottom+1): ans.append(matrix[i][right]) return ans if __name__ == '__main__': result = Solution() matrix = [[1,2,3],[4,5,6],[7,8,9]] ans = result.spiralOrder(matrix) print(ans) #Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] #Output: [1,2,3,6,9,8,7,4,5] ''' -----------------> 1 2 3 ^ | | 4 5 6 | | V 7 8 9 <---------------- 為: 123 6 987 4 5 ''' ```