/*
* 输出 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
*/
public class ForDemo03 {
public static void main(String[] args) {
int n = 5;
int x = n;
int[][] arr = new int[x][x];
int k = 0;
for (int i = 0; i < x; i++) {
// 从左到右行不变,列变
for (int j = i; j < x - i; j++) {
arr[i][j] = ++k;
}
// 右边从上向下列不变,行变
for (int j = i + 1; j < x - i; j++) {
arr[j][x - i - 1] = ++k;
}
// 底部从右向左行不变,列变
for (int j = x - i - 2; j >= i; j--) {
arr[x - i - 1][j] = ++k;
}
// 左边从下向上列不变,行变
for (int j = x - i - 2; j >= i + 1; j--) {
arr[j][i] = ++k;
}
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
|
|