0054.螺旋矩阵

54. 螺旋矩阵

给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例1:

img

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例2:

img

输入: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]

思路:

1.png

​ 本题主要是需要注意矩阵遍历时的边界,我们先定义四个边界: l e f t = 0 left=0 left=0为左边界, r i g h t = n − 1 right=n-1 right=n1为右边界, t o p = 0 top=0 top=0为上边界, b o t t o m = m − 1 bottom=m-1 bottom=m1为下边界。

  • 当顺时针向右遍历时,遍历至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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值