给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m = len(matrix)
n = len(matrix[0])
up = 0
down = m - 1
left = 0
right = n - 1
move = [(0,1),(1,0),(0,-1),(-1,0)]
mark = 0
x = 0
y = 0
res = []
while len(res) != m * n:
res.append(matrix[x][y])
if y == right and mark == 0:
mark += 1
up += 1
elif x == down and mark == 1:
mark += 1
right -= 1
elif y == left and mark == 2:
mark += 1
down -= 1
elif x == up and mark == 3:
mark = 0
left += 1
x += move[mark][0]
y += move[mark][1]
return res