给你一个 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
Python 解答:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
dires = [(0,1), (1,0), (0,-1), (-1,0)]
m = len(matrix)
n = len(matrix[0])
flag = [[True for i in range(n)] for j in range(m)]
i = 1
res = [matrix[0][0]]
index = 0
origin = [0,0]
flag[0][0] = False
while i < m*n:
one = origin[0] + dires[index][0]
two = origin[1] + dires[index][1]
if one > m-1 or one < 0 or two > n-1 or two < 0 or flag[one][two] == False:
index = (index+1)%4
continue
else:
origin[0] += dires[index][0]
origin[1] += dires[index][1]
flag[origin[0]][origin[1]] = False
res.append(matrix[origin[0]][origin[1]])
i += 1
return res
留言