题目链接
题目描述
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例
示例1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
提示
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10-
思路
模拟
直接模拟就行,设四个指针
left, right, top, bottom,分别表示左右上下的边界,按顺时针遍历即可。
值得注意的是,输入的矩阵可能不是方阵,因此要设置计数totalNum当其值变为0后,表示遍历结束。题解
class Solution:def spiralOrder(self, matrix: List[List[int]]) -> List[int]:m, n = len(matrix), len(matrix[0])ret = []if not matrix or m == 0 or n == 0:return retleft, right = 0, n - 1top, bottom = 0, m - 1totalNum = m * nwhile totalNum > 0:for i in range(left, right + 1):if totalNum == 0:breakret.append(matrix[top][i])totalNum -= 1top += 1for i in range(top, bottom + 1):if totalNum == 0:breakret.append(matrix[i][right])totalNum -= 1right -= 1for i in range(right, left - 1, -1):if totalNum == 0:breakret.append(matrix[bottom][i])totalNum -= 1bottom -= 1for i in range(bottom, top - 1, -1):if totalNum == 0:breakret.append(matrix[i][left])totalNum -= 1left += 1return ret
复杂度分析
时间复杂度:
- 空间复杂度:
