多維數組實戰核心在於**結構設計**:確定維度、長度、存儲規則、值語義。先思考再編碼,事半功倍。
需求:任意階 n 的拉丁矩陣存儲與輸出
4階示例:
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
元素值 = (行號 + 列號 + 1),超過 n 取模:data = (row + col + 1) % n == 0 ? n : (row + col + 1) % n
int n = 6;
int[][] arr = new int[n][n];
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
int data = row + col + 1;
arr[row][col] = (data <= n) ? data : data % n;
}
}
// 輸出
for (int[] rowArr : arr) {
for (int val : rowArr) System.out.print(val + " ");
System.out.println();
}
核心技巧:將二維座標映射為數值規律,利用模運算實現循環特性。
需求:10 行楊輝三角存儲與輸出
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
arr[row][col] = arr[row-1][col-1] + arr[row-1][col]int[][] arr = new int[10][10];
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col <= row; col++) {
if (col == 0) arr[row][col] = 1;
else arr[row][col] = arr[row-1][col] + arr[row-1][col-1];
}
}
// 輸出三角形狀
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col <= row; col++)
System.out.print(arr[row][col] + " ");
System.out.println();
}
col <= row 而非 col < length觀察數字規律、轉化為程序邏輯,是程序員必備基本功。