# Java螺旋数字矩阵

01 02 03 04 05 06 20 21 22 23 24 07 19 32 33 34 25 08 18 31 36 35 26 09 17 30 29 28 27 10 16 15 14 13 12 11

import java.util.Scanner;

public class MyClass {
private static int index = 1;

public static void main(String[] args) {
System.out.println("input a number[0-50]:");
int sum = 0;
try {
Scanner scanner = new Scanner(System.in);
while (true) {
sum = scanner.nextInt();
if (sum < 0) {
System.out.println("input must >= 0");
continue;
} else if (sum > 50) {
System.out.println("input must <= 50");
continue;
}
break;
}

} catch (Exception e) {
System.out.println("invalid input");
return;
}

int[][] array = new int[sum][sum];
int round = 0;
//从最外层开始循环填充每一层。
for (int i = sum; i > 0; i = i - 2) {
fill(array, i, round);
round++;
}
//打印二维数组
String format = "%0" + String.valueOf(sum * sum).length() + "d";
for (int i = 0; i < sum; i++) {
for (int j = 0; j < sum; j++) {
System.out.print(String.format(format, array[j][i]) + " ");
}
System.out.println();
}
}

private static void fill(int[][] array, int sum, int round) {
if (sum == 1) {
array[round][round] = index++;
}
//需要填充的个数(最外层数字的个数)
int length = sum * 4 - 4;
//当前是第几层
int x = round, y = round;
for (int i = 1; i <= length; i++) {
array[x][y] = index++;
//sum-1 是指最外层的右上角
if (i <= sum - 1) {
x++; //列数index++， 行数不变
//sum * 2 - 2 是指最外层的右下角
} else if (i <= sum * 2 - 2) {
y++; //行数index++， 列数不变
//sum * 3 - 3 是指最外层的左下角
} else if (i <= sum * 3 - 3) {
x--; //列数index--， 行数不变
} else {
y--; //行数index--， 列数不变
}
}
}
}