把1,2,3…n*n 的数字按照顺时针螺旋的形式填入数字矩阵

时间:2024-01-04 17:07:20

从键盘输入一个整数(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();
}
}
}

改进版:

引入状态变量,用于表示填入数字时的方向。

思路:

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