[Java] 纯文本查看 复制代码
/*
* 回行数 逻辑写法
* ps:求更简洁写法或算法写法
*/
public class Test1 {
// 此方法适用n≥3;
// n=1,2为特例,自行处理
public static void around(int n) {
int[] arr = new int[2 * n - 1];
arr[0] = n - 1;
arr[1] = n - 1;
arr[2] = n - 1;
// 不看正负,列出坐标变化的数组
if (n >= 3) {
for (int i = 3, j = 2, flag = 0; i < 2 * n - 1; i++) {
if (flag == 2) {
flag = 1;
j++;
arr = n - j;
} else {
arr = n - j;
flag++;
}
}
// 给数组加上正负
int[] symbol = { 1, 1, -1, -1 };
for (int i = 0, j = 0; i < 2 * n - 1; i++) {
arr = symbol[j++] * arr;
if (j == 4) {
j = 0;
}
}
// System.out.println(Arrays.toString(arr));
// 初始化需填入二维数组的值
int[] allNumbers = new int[n * n];
for (int i = 0; i < allNumbers.length; i++) {
allNumbers = i + 1;
}
// System.out.println(Arrays.toString(allNumbers));
// 二维数组
int[][] around = new int[n][n];
// x,y为需要转向的坐标
int x = 0, y = 0;
int getNumber = 0;
for (int j = 0, direct = 0; j < arr.length; j++, direct++) {
if (direct % 2 == 0) {
int temp = x;
x = x + arr[j];
if (temp < x) {
while (temp < x) {
around[temp][y] = allNumbers[getNumber];
temp++;
getNumber++;
}
} else if (x < temp) {
while (x < temp) {
around[temp][y] = allNumbers[getNumber];
temp--;
getNumber++;
}
}
} else {
int temp = y;
y = y + arr[j];
if (temp < y) {
while (temp < y) {
around[x][temp] = allNumbers[getNumber];
temp++;
getNumber++;
}
} else if (y < temp) {
while (y < temp) {
around[x][temp] = allNumbers[getNumber];
temp--;
getNumber++;
}
}
}
}
// 最后一个数,不会在循环中被赋值,手动赋值
around[x][y] = allNumbers[allNumbers.length - 1];
// 打印二维数组
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(around[j] + "\t");
}
System.out.println();
}
}
}
}