螺旋矩陣
題目描述:
給定一個(gè)包含 m x n 個(gè)元素的矩陣(m 行, n 列),請(qǐng)按照順時(shí)針螺旋順序,返回矩陣中的所有元素。
示例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]
解題思路:
整體的算法邏輯是,通過(guò)遍歷整個(gè)矩陣的每一行和每一列,而該遍歷的路徑是,從第一行從左向右開(kāi)始,直到末尾,然后向下直到末尾,始終保持一個(gè)
右→下→左→上的遍歷路徑,直到遍歷完成每一個(gè)元素-
特別注意三種情況,第一是
left == right and top == bottom中心剩下一個(gè)數(shù)值 ——— |3| ——— -
第二種是
top == bottom中心橫向多個(gè)數(shù)值 ————————— |3 4 5 6| ————————— -
第三種是
left == right中心縱向多個(gè)數(shù)值 ——— |2| |3| |4| ———
Python源碼:
from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
left = top = 0
right = len(matrix[0]) - 1
bottom = len(matrix) - 1
result = []
while left < right and top < bottom:
for i in range(left, right):
result.append(matrix[top][i])
for i in range(top, bottom):
result.append(matrix[i][right])
for i in range(right, left, -1):
result.append(matrix[bottom][i])
for i in range(bottom, top, -1):
result.append(matrix[i][left])
left += 1
right -= 1
top += 1
bottom -= 1
if left == right and top == bottom:
result.append(matrix[top][left])
elif left == right:
for i in range(top, bottom + 1):
result.append(matrix[i][left])
elif top == bottom:
for i in range(left, right + 1):
result.append(matrix[top][i])
return result
歡迎關(guān)注我的github:https://github.com/UESTCYangHR