赞
踩
给你一个 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]: # 位移方向 arrow = [(0, 1), (1, 0), (0, -1), (-1, 0)] m, n = len(matrix), len(matrix[0]) x, y = 0, 0 res = [] while True: res.append(matrix[x][y]) matrix[x][y] = None for dx, dy in arrow: # 满足条件就移动,不满足换个方向接着走 while 0 <= x + dx < m and 0 <= y + dy < n and matrix[x + dx][y + dy] is not None: x, y = x + dx, y + dy res.append(matrix[x][y]) matrix[x][y] = None # 走完一圈走内圈,无路可走直接退出 if 0 <= x < m and 0 <= y + 1 < n and matrix[x][y + 1] is not None: x, y = x, y + 1 else: break return res
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。