首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

LeetCode 螺旋矩陣 II:生成順時針遞增的正方形矩陣

     編輯:關於C++

題目描述

給定一個正整數 n,請生成一個包含從 1 到 n² 的所有元素,且按順時針螺旋順序填充的 n × n 正方形矩陣。

範例:

輸入: n = 3
輸出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

解題思路

這道題是「螺旋矩陣」的逆向操作:不是讀取,而是寫入。因為矩陣固定為正方形,我們只需維護四條邊界(上、下、左、右),逐層向內縮減即可。特別注意當 n 為奇數時,中心會剩下一個單獨的格子,需額外處理。

  1. 初始化 left = 0, right = n-1, top = 0, bottom = n-1,以及計數器 num = 1。
  2. 當 left < right 且 top < bottom 時,依序填充:
    • 頂行:從左到右(不含右端)
    • 右欄:從上到下(不含下端)
    • 底行:從右到左(不含左端)
    • 左欄:從下到上(不含上端)
  3. 每完成一圈,四條邊界同時向內收縮:left++, right--, top++, bottom--。
  4. 若最終 left == right 且 top == bottom,說明有中心點,直接填入剩餘的 num。

參考代碼 (Python)

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

複雜度分析

  • 時間複雜度:O(n²) —— 需遍歷矩陣每個位置一次。
  • 空間複雜度:O(1) 額外空間(不含輸出矩陣)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved