【leetcode刷题】59 spiral matrix II (python)

本文提供了一个解决LeetCode螺旋矩阵II问题的Python代码实现。通过定义一个类Solution和方法generateMatrix,使用round变量记录当前轮数,按上右下左顺序填充矩阵,直至完成。特别注意当上下边界重合时的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接
https://leetcode.com/problems/spiral-matrix-ii
解题思路
用round记录当前处于第几轮,按照上右下左的顺序不断转圈输出即可。但需要注意的是当上下重合为一行时需要判断一下,中止程序。
代码

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        matrix = [[0 for i in range(n)] for j in range(n)]
        round = 0
        index = 1
        # fill the first row
        while round<n//2+1:
            for col in range(round, n-round):
                matrix[round][col] = index
                index += 1
            for row in range(round+1, n-1-round):
                matrix[row][n-1-round] = index
                index += 1
            if n-1-round==round:
                break
            for col in range(n-round-1,round-1,-1):
                matrix[n-1-round][col] = index
                index += 1
            for row in range(n-2-round, round, -1):
                matrix[row][round] = index
                index += 1
            round += 1
        return matrix

参考链接
https://blog.youkuaiyun.com/nerv3x3/article/details/41628823

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值