作战大师Qcm —— 原创代码, 转载请附注出处。
/**
* @name getVortexNumber
* @param length
* @explain 获得 [回形数组]
*/
private static void getVortexNumber(int length) {
int num = 1; // 计数器
int len = length; // 矩阵 的 最大边长
int border = length; // "从外到内"的每一圈正方形矩阵 的 边长
int[][] arr = new int[len][len];
while (border != 0){ // 按上右下左顺序一层层获取二维坐标, 并赋值
for (int i = len-border; i < border-1; i++) arr[len-border][i] = num++;
for (int i = len-border; i < border-1; i++) arr[i][border-1] = num++;
for (int i = border-1; i >len-border; i--) arr[border-1][i] = num++;
for (int i = border-1; i >len-border; i--) arr[i][len-border] = num++;
border--;
}
// 解决"奇数边长"导致最后一个数为空的问题
if (length%2 == 1) arr[len/2][len/2] = len * len;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j]<10) System.out.print(arr[i][j]+" ");
else System.out.print(arr[i][j]+" ");
}System.out.println();
}
}
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