Python螺旋矩陣遍歷
在 Python 中以螺旋順序遍歷並列出二維矩陣的元素。
概述
螺旋矩陣遍歷是一個經典的多維數組問題。它需要順時針遍歷外部邊界並逐漸縮小邊界。
我們維護四個指標:「top」、「bottom」、「left」和「right」來追蹤未存取的矩陣部分的邊界。
透過從左到右、從上到下、從右到左、從下到上的順序遍歷,我們系統地覆蓋了所有單元格。
程式碼和執行輸出
順時針螺旋遍歷顯示索引操縱。
spiral.py
在編輯器中嘗試def spiral_order(matrix):
if not matrix:
return []
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
# Traverse Right
for col in range(left, right + 1):
result.append(matrix[top][col])
top += 1
# Traverse Down
for row in range(top, bottom + 1):
result.append(matrix[row][right])
right -= 1
if top <= bottom:
# Traverse Left
for col in range(right, left - 1, -1):
result.append(matrix[bottom][col])
bottom -= 1
if left <= right:
# Traverse Up
for row in range(bottom, top - 1, -1):
result.append(matrix[row][left])
left += 1
return result
grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("Matrix Spiral Order:")
print(spiral_order(grid))端子輸出
Matrix Spiral Order:
[1, 2, 3, 6, 9, 8, 7, 4, 5]逐步實施
- 2D圖形渲染和螺旋路徑追蹤
- 資料引擎中的網格佈局導航模式
- 進階演算法評估測試
常見問題解答
螺旋遍歷的時間複雜度是多少?
時間複雜度為 O(m * n),其中 m 是行,n 是列,因為我們只訪問網格中的每個單元一次。