從鍵盤輸入一個整數(1~20)
則以該數字為矩陣的大小,把1,2,3…n*n 的數字按照順時針螺旋的形式填入其中。例如:
輸入數字2,則程序輸出:
1 2
4 3
輸入數字3,則程序輸出:
1 2 3
8 9 4
7 6 5
輸入數字4, 則程序輸出:
1 ? ?2 ?3 ? 4
12 13 14 5
11 16 15 6
10 9 ? 8 ?7
?
代碼:
public class FillNumber {public static void main(String[] args) {int n = 5;int[][] arr = getMatrix(n);show(arr, n);}public static int[][] getMatrix(int n) {int val = 1; // 從1開始填入數字int[][] arr = new int[n][n];int i = 0;int row, col;int left, right, top, bottom;// 循環的圈數while (i <= (n - 1) / 2) {row = i;col = i;left = row; // 圈的最左端right = n - 1 - i; // 圈的最右端top = left; // 圈的頂端bottom = right; // 圈的底端// 向右while (col <= right) {arr[row][col] = val;val++;col++;}col = right;row += 1;// 向下while (row <= bottom) {arr[row][col] = val;val++;row++;}row = bottom;col -= 1;// 向左while (col >= left) {arr[row][col] = val;val++;col--;}col = left;row -= 1;// 向上while (row > top) {arr[row][col] = val;val++;row--;}i++;}return arr;}public static void show(int[][] arr, int n) {for (int i = 0; i < n; ++i) {for (int j = 0; j < n; ++j) {System.out.printf("%-2d ", arr[i][j]);}System.out.println();}} }
12…n逆序數,?
改進版:
引入狀態變量,用于表示填入數字時的方向。
思路:
順時針螺旋輸出矩陣?1.行坐標不變列坐標遞增,當列坐標超出最大范圍或者要填充的位置已經被填充過,則跳轉到步驟2,
2.行坐標遞增列坐標不變,當行坐標超過最大范圍或者要填充的位置已經被填充過,則跳轉到步驟3
3.行坐標不變列坐標遞減,當列坐標小于最小范圍或者要填充的位置已經被填充過,則跳轉到步驟4
4.行坐標遞減列坐標不變,當行坐標小于最小范圍或者要填充的位置已經被填充過,則跳轉到步驟1
循環執行以上四個步驟,每執行一個步驟則填充一個數據,直到全部數據填充完則結束
public static int[][] getMatrix1(int n) {int[][] arr = new int[n][n];char type = 1;int val = 1;int row = 0;int col = 0;while (val <= n * n) {arr[row][col] = val;val++;// 根據填入數字的方向 來確定下一個要填入數據的row,col// 向右if (type == 1) {col++;if (col == n || arr[row][col] != 0) {col--;row++;type = 2;}}// 向下else if (type == 2) {row++;if (row == n || arr[row][col] != 0) {row--;col--;type = 3;}}// 向左else if (type == 3) {col--;if (col == -1 || arr[row][col] != 0) {col++;row--;type = 4;}}// 向上else if (type == 4) {row--;if (row == 0 || arr[row][col] != 0) {row++;col++;type = 1;}}}return arr;}
效果:
當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
?