数据结构Python版---生成螺旋矩阵(Day5)

文章目录

    • 1.1 ⭐算法原理:
    • 1.2 连续数组长度

1.1 ⭐算法原理:

生成螺旋矩阵原理
通过模拟矩阵填充来解决,像蜗牛的螺旋一样,从外往里旋。

1.2 连续数组长度

给定一个正整数 n,生成一个包含 1 到 n^2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

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

通过模拟矩阵填充的过程来解决,使用四个变量 top、bottom、left、right 来表示当前矩阵的上、下、左、右边界。


```python
class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        matrix = [[0] * n for _ in range(n)]

你可能感兴趣的:(数据结构Python版,python,算法,开发语言,leetcode,数据结构)