力扣刷题——59.螺旋矩阵II
题目
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
1 <= n <= 20
标准答案
class Solution:def generateMatrix(self, n: int) -> List[List[int]]:# for _ in range(n)列表推导式,会重复执行前面的[0] * n 一共n次matrix = [[0] * n for _ in range(n)]# 第一维度-行;第二维度-列。left, right, top, bottom = 0, n - 1, 0, n - 1num = 1while left <= right and top <= bottom:# 从左到右for j in range(left, right + 1):matrix[top][j] = numnum += 1# 从上到下for i in range(top + 1, bottom + 1):matrix[i][right] = numnum += 1# 保证至少有两行两列时,才执行“右→左”和“下→上”,#否则可能会覆盖或重复填数if top < bottom and left < right:# 从右到左# 每次循环 j 减 1,表示从右往左走for j in range(right - 1, left, -1):matrix[bottom][j] = numnum += 1# 从下到上for i in range(bottom, top, -1):matrix[i][left] = numnum += 1left += 1right -= 1top += 1bottom -= 1return matrix
思路总结
一共四个方向,逐个方向去走,每个方向都有一个维度是固定的。从外圈向内圈螺旋填数,每走完一圈收缩边界,直到填满 n² 个数。
-
初始化边界:
top = 0, bottom = n-1 (行范围)
eft = 0, right = n-1 (列范围)
num = 1 (从 1 填到 n²) -
按圈循环填数字(每次四个方向):
从左到右:固定行 top,列从 left → right
从上到下:固定列 right,行从 top+1 → bottom
从右到左:固定行 bottom,列从 right-1 → left+1
从下到上:固定列 left,行从 bottom → top+1 -
收缩边界:
top += 1, bottom -= 1, left += 1, right -= 1
直到所有数字填完
复杂度:
时间 O(n²),空间 O(1)