1. 程式人生 > 實用技巧 >【leetcode - 54】螺旋矩陣 medium

【leetcode - 54】螺旋矩陣 medium

給定一個包含m x n個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。

示例1:

輸入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
輸出: [1,2,3,6,9,8,7,4,5]
示例2:

輸入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
輸出: [1,2,3,4,8,12,11,10,9,5,6,7]

比較暴力的迴圈遍歷方法,構建方向向量右下左上,通過取餘判斷是否已經迴圈了一遍所有方向

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        
if not matrix: return matrix rownum = len(matrix) colnum = len(matrix[0]) #記錄是否到達迴圈 indexnum = 0 #設定方向向量 右下左上 row = [0,1,0,-1] col = [1,0,-1,0] #記錄是否遍歷過這個元素位置 mm = [] #開始遍歷 x,y = 0,0 res = []
for i in range(rownum*colnum): res.append(matrix[x][y]) mm.append((x,y)) new_x = x+row[indexnum] new_y = y+col[indexnum] if 0<=new_x<rownum and 0<=new_y<colnum and (new_x,new_y) not in mm: x,y = new_x,new_y
else: indexnum = (indexnum+1)%4 x,y = x+row[indexnum],y+col[indexnum] return res