/**
* 打印螺旋数组 如:
* 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 LuoXuanJuZhen {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
print(len);
}
private static void print(int len) {
int levels = len / 2 + len % 2;
int x = 0;
int y = 0;
int i = 0;
int count = 1;
int[][] arr = new int[len][len];
while (i < levels) {
//打印第一行的数,以5X5的矩阵为例,第一次循环输出1 2 3 4 5
for (; y < len - i; y++) {
arr[x][y] = count;
count++;
}
y--;
x++;
//打印最后一列的数6 7 8 9
for (; x < len - i; x++) {
arr[x][y] = count;
count++;
}
x--;
y--;
//打印最后一行的数10 11 12 13
for (; y >= i; y--) {
arr[x][y] = count++;
}
y++;
x--;
//打印第一列的数14 15 16
for (; x > i; x--) {
arr[x][y] = count++;
}
x++;
y++;
i++;
}
for (int m = 0; m < len; m++) {
for (int n = 0; n < len; n++) {
System.out.print(arr[m][n] + "\t");
}
System.out.println();
}
}
} |