题目描述
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
python代码
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix: return []
m, n = len(matrix), len(matrix[0])
x = y = di = 0
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
res = []
visited = []
for i in range(m*n):
res.append(matrix[x][y])
visited.append([x, y])
tx, ty = x+dx[di], y+dy[di]
if 0<=tx<m and 0<=ty<n and [tx, ty] not in visited:
x, y = tx, ty
else:
di = (di+1)%4
x, y = x+dx[di], y+dy[di]
return res
Reference