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依次填入矩阵中并返回。
实现代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13class 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内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复