我是靠谱客的博主 无私绿草,这篇文章主要介绍LeetCode-59 Spiral Matrix II,现在分享给大家,希望可以做个参考。

Description

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

Submissions

这道题是54题的改进版,因此采用相同的解题思路,可回顾https://blog.csdn.net/weixin_41875619/article/details/107417397
而与54题不同之处就在于首先需要定义n个分别包含n个元素的数组矩阵。然后利用54题的变换螺旋规则,将1到n2-1依次填入矩阵中并返回。
实现代码如下:

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        res = [[0 for _ in range(n)] for _ in range(n)]
        i, j, di, dj = 0, 0, 0, 1
        if res != []:
            for k in range(1,n*n+1):
                res[i][j] = k
                if res[(i + di) % len(res)][(j + dj) % len(res[0])] != 0:
                    di, dj = dj, -di
                i += di
                j += dj
        return res

最后

以上就是无私绿草最近收集整理的关于LeetCode-59 Spiral Matrix II的全部内容,更多相关LeetCode-59内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(107)

评论列表共有 0 条评论

立即
投稿
返回
顶部