[Array]54. Spiral Matrix

  • 分類:Array
  • 時間復雜度: O(n*m)

54. 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]

代碼:

方法:

class Solution:
    def spiralOrder(self, matrix: 'List[List[int]]') -> 'List[int]':
        
        res=[]
        
        if matrix==None or matrix==[] or matrix==[[]]:
            return res
        
        top=0
        left=0
        right=len(matrix[0])-1
        bottom=len(matrix)-1
        row,col=0,0
        
        while left<right and top<bottom:
            while col<right:
                res.append(matrix[row][col])
                col+=1
            while row<bottom:
                res.append(matrix[row][col])
                row+=1
            while col>left:
                res.append(matrix[row][col])
                col-=1
            while row>top:
                res.append(matrix[row][col])
                row-=1
            top+=1
            left+=1
            col+=1
            row+=1
            right-=1
            bottom-=1

        if left==right and top==bottom:
            res.append(matrix[top][left])
        elif top==bottom:
            while left<=right:
                res.append(matrix[top][left])
                left+=1
        elif left==right:
            while top<=bottom:
                res.append(matrix[top][left])
                top+=1
            
        return res

討論:

1.最后剩余的這三種情況最重要,要進行分類討論=。=
2.col和row別忘了+1

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容