62,614
社区成员
发帖
与我相关
我的任务
分享
JDK5
public class Test {
public static void main(String[] args) {
int n = 7;
int[][] m = new int[n][n];
int[] d = new int[]{ 1, 0 , 0, 1, -1, 0, 0, -1};
int[] a = new int [n * 2];
a[0] = n - 1;
a[n * 2 -1 ] = 1;
int s = n;
for (int i = 1; i < n * 2 -1 ; i += 2) {
a[i] = a[i + 1] = --s;
}
int c = 0;
int w = 1;
int x = 0;
int y = 0;
for (int i = 0; i < a.length; ++i) {
c %= 4;
for (int j = 0; j < a[i]; j++) {
m[x][y] = w++;
x += d[c * 2];
y += d[c * 2 + 1];
}
c++;
}
for (int k = 0; k < n; k++) {
for (int j = 0; j < n; j++) {
System.out.print(String.format("%4d", m[k][j]));
}
System.out.println();
}
}
}