Leetcode刷题记录30——螺旋矩阵
题源:https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-100-liked
题目描述:
思路一:
💡 解题思路:模拟边界法(Layer by Layer)
我们可以把矩阵想象成一圈圈的**“洋葱皮”**,每一层从外向内顺时针访问:
- 先访问最上面一行(从左到右)
- 然后访问最右边一列(从上到下)
- 接着访问最下面一行(从右到左)
- 最后访问最左边一列(从下到上)
然后向内收缩边界,继续遍历下一层,直到所有元素都被访问完为止。
代码如下:
class Solution(object):def spiralOrder(self, matrix):""":type matrix: List[List[int]]:rtype: List[int]"""top = 0bottom = len(matrix) - 1left = 0right = len(matrix[0]) - 1result = []while top <= bottom and left <= right:# 从左到右for j in range(left, right + 1):result.append(matrix[top][j])top += 1# 从上到下:for i in range(top, bottom + 1):result.append(matrix[i][right])right -= 1# 从右到左(判断是否还有行)if left <= right and top <= bottom:for j in range(right, left - 1, -1):result.append(matrix[bottom][j])bottom -= 1# 从下到上(判断是否还有列)if left <= right and top <= bottom:for i in range(bottom, top - 1, -1):result.append(matrix[i][left])left += 1return result
执行时间如下: