力扣刷題——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
思路總結
一共四個方向,逐個方向去走,每個方向都有一個維度是固定的。從外圈向內圈螺旋填數,每走完一圈收縮邊界,直到填滿 n2 個數。
-
初始化邊界:
top = 0, bottom = n-1 (行范圍)
eft = 0, right = n-1 (列范圍)
num = 1 (從 1 填到 n2) -
按圈循環填數字(每次四個方向):
從左到右:固定行 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(n2),空間 O(1)