題目描述:
給定一個正整數 n,生成一個 n x n 的矩陣,將數字 1 到 n² 以螺旋順序(順時針)填入矩陣中。
解題思路:
使用模擬法,維護四個邊界:top、bottom、left、right,從數字 1 開始依序填入:
top++。right--。bottom--。left++。重複以上四步直到填完 n² 個數字。每次填入後邊界收縮,最終完成整個螺旋矩陣。
時間複雜度:O(n²) — 每個格子恰好被填入一次,總共 n² 個格子。
空間複雜度:O(1) — 除了輸出矩陣外,只使用常數額外空間(邊界變數與計數器)。
1. Create n x n matrix filled with 0 2. Initialize boundaries: top=0, bottom=n-1, left=0, right=n-1 3. Initialize num = 1 4. While num <= n*n: a. Fill top row from left to right, then top++ b. Fill right column from top to bottom, then right-- c. Fill bottom row from right to left, then bottom-- d. Fill left column from bottom to top, then left++ 5. Return matrix
方向陣列模擬法:使用方向向量 (dx, dy) 陣列 [(0,1),(1,0),(0,-1),(-1,0)] 模擬螺旋移動,遇到邊界或已填入的格子則轉向。時間 O(n²),空間 O(1)。相較於邊界收縮法,邏輯更直觀但需要額外判斷是否已訪問。
遞迴法(Layer-by-Layer):每次遞迴填入最外圈一層,然後遞迴處理內層子矩陣。時間 O(n²),空間 O(n) 遞迴深度。實作較不直覺,且遞迴深度隨 n 增長。