輸入 N (2≤N≤9),輸出 N×N 矩陣,數字 1~N² 從左上角起順時針螺旋填充。
N=3: N=4:
1 2 3 1 2 3 4
8 9 4 12 13 14 5
7 6 5 11 16 15 6
10 9 8 7
維護四個方向枚舉(右、下、左、上),當前位置撞牆或遇到已填數字時,順時針轉向。
import java.util.Arrays;
import java.util.Scanner;
public class SpiralMatrix {
enum Direction { RIGHT, DOWN, LEFT, UP }
public int[][] buildSpiral(int n) {
int[][] matrix = new int[n][n];
for (int[] row : matrix) Arrays.fill(row, 0); // 0 表示未填充
int row = 0, col = 0;
int counter = 1;
Direction dir = Direction.RIGHT;
while (true) {
if (matrix[row][col] == 0) {
matrix[row][col] = counter++;
// 嘗試按當前方向前進
switch (dir) {
case RIGHT:
if (col + 1 < n && matrix[row][col + 1] == 0) col++;
else { dir = Direction.DOWN; row++; }
break;
case DOWN:
if (row + 1 < n && matrix[row + 1][col] == 0) row++;
else { dir = Direction.LEFT; col--; }
break;
case LEFT:
if (col - 1 >= 0 && matrix[row][col - 1] == 0) col--;
else { dir = Direction.UP; row--; }
break;
case UP:
if (row - 1 >= 0 && matrix[row - 1][col] == 0) row--;
else { dir = Direction.RIGHT; col++; }
break;
}
} else {
break; // 回到起點或填滿,結束
}
}
return matrix;
}
public void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int val : row) {
System.out.printf("%4d", val); // 每個數字佔 4 字符,右對齊
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入矩陣階數 N (2-9): ");
int n = sc.nextInt();
if (n < 2 || n > 9) {
System.out.println("N 超出範圍");
return;
}
SpiralMatrix sm = new SpiralMatrix();
int[][] result = sm.buildSpiral(n);
sm.printMatrix(result);
}
}
*
* * *
* * * * *
* * * * * * *
* * * * *
* * *
*
用變量 i 表示當前行距離中線的偏移(-n 到 n),flag 控制增減方向。
public class DiamondPrinter {
public void printDiamond(int n) {
if (n <= 0) return;
for (int i = 0; i < 2 * n - 1; i++) {
int spaces, stars;
if (i < n) { // 上半部含中線
spaces = n - 1 - i;
stars = 2 * i + 1;
} else { // 下半部
spaces = i - n + 1;
stars = 2 * (2 * n - 1 - i) - 1;
}
// 打印空格
for (int s = 0; s < spaces; s++) System.out.print(" "); // 兩空格對齊
// 打印星號(中間帶空格美觀)
for (int s = 0; s < stars; s++) System.out.print("* ");
System.out.println();
}
}
public static void main(String[] args) {
new DiamondPrinter().printDiamond(5);
}
}
2*i+1 (上半) 或 2*(2n-1-i)-1 (下半)// 空心菱形:只打印邊框
if (s == 0 || s == stars - 1) System.out.print("* ");
else System.out.print(" ");
// 指定字符菱形
printDiamond(4, '#'); // 重載方法接受字符參數
螺旋矩陣體現狀態機思維,菱形打印體現數學規律提煉。兩題皆屬基礎算法訓練,關鍵在於:
建議動手嘗試:逆時針螺旋、帶間隔菱形、多層嵌套菱形。