原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-hard/xw3ng2/
解法一(python):
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
m, n = len(matrix), len(matrix[0])
result = []
top, bottom = 0, m - 1
left, right = 0, n - 1
while len(result) < m * n:
# 从左到右
for j in range(left, right + 1):
result.append(matrix[top][j])
top += 1
if len(result) == m * n:
break
# 从上到下
for i in range(top, bottom + 1):
result.append(matrix[i][right])
right -= 1
if len(result) == m * n:
break
# 从右到左
for j in range(right, left - 1, -1):
result.append(matrix[bottom][j])
bottom -= 1
if len(result) == m * n:
break
# 从下到上
for i in range(bottom, top - 1, -1):
result.append(matrix[i][left])
left += 1
return result
思路:
-
初始化一个空列表
result
用于存储螺旋顺序的元素。 -
初始化四个变量
top
,bottom
,left
,right
分别表示当前螺旋区域的边界。 -
使用一个循环来遍历矩阵中的元素,直到
result
的长度等于矩阵元素的总数。 -
在每一轮循环中,按照顺时针的顺序遍历当前螺旋区域的元素,并将其添加到
result
中。 -
更新螺旋区域的边界:上边界
top
向下移动一行;右边界right
向左移动一列;下边界bottom
向上移动一行;左边界left
向右移动一列。