数组Ⅱ"/>
Leetcode 螺旋数组Ⅱ
题目描述
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
分析:
从左到右、从上到下、从右到左、从下到上赋值矩阵
思路解析
class Solution:def generateMatrix(self, n: int) -> [[int]]:left, right, top, bottom = 0, n - 1, 0, n - 1matrix = [[0 for _ in range(n)] for _ in range(n)]num, tar = 1, n * nwhile num <= tar:for i in range(left, right + 1): # left to rightmatrix[top][i] = numnum += 1top += 1for i in range(top, bottom + 1): # top to bottommatrix[i][right] = numnum += 1right -= 1for i in range(right, left - 1, -1): # right to leftmatrix[bottom][i] = numnum += 1bottom -= 1for i in range(bottom, top - 1, -1): # bottom to topmatrix[i][left] = numnum += 1left += 1return matrix
更多推荐
Leetcode 螺旋数组Ⅱ
发布评论