源代码
可能是最简单的实现代码了
参数命名可能有所不足,望不吝赐教
package spiralarray;
import java.util.*;
public class SpiralArray {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int n = keyboard.nextInt();//the side length of square
int l = n / 2;//the layers of square
int v = 0;//next layer starting value
int[] a = new int[n * n];//stored array
if (n % 2 == 1) a[l * n + l] = n * n;//if exist the 1*1 square
for (int i = 0; i < l; i++) {
for (int j = 0; j < n - 2 * i - 1; j++) {
a[n * i + i + j] = v + j + 1;//upper left
a[n * i + n * j + n - i - 1] = v + j + n - 2 * i;//upper right
a[n * n - 1 - (n * i + i + j)] = v + j + 2 * n - 4 * i - 1;//lower right
a[n * n - 1 - (n * i + n * j + n - i - 1)] = v + j + 3 * n - 6 * i - 2;//lower left
}
v += 4 * (n - 2 * i - 1);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[n * i + j] + (j == n - 1 ? "\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
10
1 2 3 4 5 6 7 8 9 10
36 37 38 39 40 41 42 43 44 11
35 64 65 66 67 68 69 70 45 12
34 63 84 85 86 87 88 71 46 13
33 62 83 96 97 98 89 72 47 14
32 61 82 95 100 99 90 73 48 15
31 60 81 94 93 92 91 74 49 16
30 59 80 79 78 77 76 75 50 17
29 58 57 56 55 54 53 52 51 18
28 27 26 25 24 23 22 21 20 19