給定一個正整數 n,請生成一個包含從 1 到 n² 的所有元素,且按順時針螺旋順序填充的 n × n 正方形矩陣。
範例:
輸入: n = 3
輸出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
這道題是「螺旋矩陣」的逆向操作:不是讀取,而是寫入。因為矩陣固定為正方形,我們只需維護四條邊界(上、下、左、右),逐層向內縮減即可。特別注意當 n 為奇數時,中心會剩下一個單獨的格子,需額外處理。
left = 0, right = n-1, top = 0, bottom = n-1,以及計數器 num = 1。left < right 且 top < bottom 時,依序填充:
left++, right--, top++, bottom--。left == right 且 top == bottom,說明有中心點,直接填入剩餘的 num。class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
left, right, top, bottom = 0, n - 1, 0, n - 1
num = 1
res = [[0] * n for _ in range(n)]
while left < right and top < bottom:
for i in range(left, right):
res[top][i] = num
num += 1
for i in range(top, bottom):
res[i][right] = num
num += 1
for i in range(right, left, -1):
res[bottom][i] = num
num += 1
for i in range(bottom, top, -1):
res[i][left] = num
num += 1
left += 1
right -= 1
top += 1
bottom -= 1
if left == right and top == bottom:
res[top][left] = num
return res