螺旋矩阵题总结 (顺时针打印矩阵)python

本文总结了两道螺旋矩阵题目,分别给出了顺时针打印矩阵的解题思路和Python代码。第一题关注拐点边界条件,确保正确顺序;第二题为第一题的变种,解题方法相似。

原题链接:
54. 螺旋矩阵 (按照顺时针顺序打印给定矩阵)
59. 螺旋矩阵 2 (给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。)

第一道题的解题思路:按照从左到右,从上到下,从右到左,从下到上的顺序依次打印矩阵中的数字,要注意的是判断拐点的边界条件,和时刻保持左不能大于右,上不能大于下。

代码如下:

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix: 
            return []
        left = 0
        top = 0
        bottom = len(matrix) - 1
        right  = len(matrix[0]) - 1
        res = []
        
        while left <= right and top <= bottom:
            # from left to right
            for i in range(left, right + 1):
                res.append(matrix[top][i])
            top += 1
            if top > bottom:
                break
                
            #from top to bottom 
            for i in range(top, bottom + 1):
                res.append(matrix[i][right])
            right -= 1
            if left > right:
                break
            
            #from right to left
            for i in range(right, left - 1, -1):
                res.append(matrix[bottom][i])
            bottom -= 1

            #from bottom to top
            for i in range(bottom, top - 1, -1):
                res.append(matrix[i][left])
            left += 1
        return res

第二道题是第一道题的变种,解题思路类似。
代码如下

class Solution:
    def generateMatrix(self, n: int) -> [[int]]:
        if not n:
            return []
        left, right, top, bottom = 0, n - 1, 0, n - 1
        mat = [[0 for _ in range(n)] for _ in range(n)]
        num, tar = 1, n * n
        while num <= tar:
            for i in range(left, right + 1): # left to right
                mat[top][i] = num
                num += 1
            top += 1
            for i in range(top, bottom + 1): # top to bottom
                mat[i][right] = num
                num += 1
            right -= 1
            for i in range(right, left - 1, -1): # right to left
                mat[bottom][i] = num
                num += 1
            bottom -= 1
            for i in range(bottom, top - 1, -1): # bottom to top
                mat[i][left] = num
                num += 1
            left += 1
        return mat
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值