給定正整數 N,輸出 N×N 的順時針螺旋矩陣,數字從 1 遞增至 N²。例如 N=5:
1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
採用「方向向量 + 邊界收縮」策略:
sum)。py = px; px = 0; pn-- (步數減 1)px = -py; py = 0 (步數不變,但下一輪水平會再減 1)rect[x][y]),輸出時再轉回 (rect[j][i])。import java.util.Scanner;
public class SpiralMatrix {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] rect = new int[n + 1][n + 1]; // 1-based 索引方便邏輯
int x = 0, y = 1; // 當前座標
int px = 1, py = 0; // 方向增量 (初始向右)
int pn = n; // 當前方向剩餘步數
int sum = n; // 當前方向終點計數
for (int i = 1; i <= n * n; i++) {
x += px; y += py;
rect[x][y] = i;
if (i == sum) { // 到達轉角
if (px != 0) { // 水平 -> 垂直
pn--; // 步數遞減
sum += pn;
py = px; px = 0;
} else { // 垂直 -> 水平
sum += pn;
px = -py; py = 0;
}
}
}
// 列印 (轉置回正確行列)
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(rect[j][i] + "\t");
}
System.out.println();
}
}
}
輸入 5,Console 輸出即為上述 5×5 螺旋矩陣。演算法時間複雜度 O(N²),空間複雜度 O(N²),邏輯緊湊無冗餘判斷。