54. 螺旋矩阵
给你一个 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]
思路:
本题主要是需要注意矩阵遍历时的边界,我们先定义四个边界: l e f t = 0 left=0 left=0为左边界, r i g h t = n − 1 right=n-1 right=n−1为右边界, t o p = 0 top=0 top=0为上边界, b o t t o m = m − 1 bottom=m-1 bottom=m−1为下边界。
- 当顺时针向右遍历时,遍历至
right
截止,同时top
向下移,即 t o p = t o p + 1 top=top+1 top=top+1,当 t o p > b o t t o m top>bottom top>bottom时,停止遍历; - 当顺时针向下遍历时,遍历至
bottom
截止,同时right
向左移,即 r i g h t = r i g h t + 1 right=right+1 right=right+1,当 r i g h t < l e f t right<left right<left时,停止遍历; - 当顺时针向左遍历时,遍历至
left
截止,同时bottom
向上移,即 b o t t o m = b o t t o m + 1 bottom=bottom+1 bottom=bottom+1;当 b o t t o m < t o p bottom<top bottom<top时,停止遍历; - 当顺时针向上遍历时,遍历至
top
截止,同时left
向右移,即 l e f t = l e f t + 1 left=left+1 left=left+1,当 l e f t > r i g h t left>right left>right时,停止遍历。
代码如下:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m = len(matrix) # 矩阵的行数
n = len(matrix[0]) # 矩阵的列数
l = list()
# 当矩阵为空时,返回空列表
if not matrix:
return l
i, j = 0, 0
top, bottom, left, right = 0, m-1, 0, n-1 # 定义上下左右四个边界,每遍历完一个边就收缩边界
while True:
for i in range(left, right+1): # 顺时针向右走
l.append(matrix[top][i])
top += 1 # top边界向下收缩
if top > bottom:
break
for j in range(top, bottom+1): # 顺时针向下走
l.append(matrix[j][right])
right -= 1 # right边界向左收缩
if right < left:
break
for k in range(right, left-1, -1): # 顺时针向左走
l.append(matrix[bottom][k])
bottom -= 1 # bottom边界向上收缩
if bottom < top:
break
for o in range(bottom, top-1, -1): # 顺时针向上走
l.append(matrix[o][left])
left += 1 # left边界向右收缩
if left > right:
break
return l