給定一個 m×n 矩陣(不一定是正方形),按順時針螺旋順序輸出所有元素。
範例:
輸入: [[1,2,3],[4,5,6],[7,8,9]]
輸出: [1,2,3,6,9,8,7,4,5]
維護四個邊界:top, bottom, left, right。循環條件 left <= right && top <= bottom。每圈依序遍歷:
left → right,top++。top → bottom,right--。top <= bottom,底行:right → left,bottom--。left <= right,左欄:bottom → top,left++。條件判斷避免重複遍歷單行/單列情況。
class Solution:
def spiralOrder(self, matrix):
if not matrix: return []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
res = []
while left <= right and top <= bottom:
for i in range(left, right + 1):
res.append(matrix[top][i])
top += 1
for i in range(top, bottom + 1):
res.append(matrix[i][right])
right -= 1
if top <= bottom:
for i in range(right, left - 1, -1):
res.append(matrix[bottom][i])
bottom -= 1
if left <= right:
for i in range(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1
return res