关于打印出
1 2 9 10 25 26 49 50 81 82
4 3 8 11 24 27 48 51 80 83
5 6 7 12 23 28 47 52 79 84
16 15 14 13 22 29 46 53 78 85
17 18 19 20 21 30 45 54 77 86
36 35 34 33 32 31 44 55 76 87
37 38 39 40 41 42 43 56 75 88
64 63 62 61 60 59 58 57 74 89
65 66 67 68 69 70 71 72 73 90
100 99 98 97 96 95 94 93 92 91
的数组。
一直保持循环的思维,错将if用while来代替,运行了半天也没发现原因...幸好虹哥帮指正了,还有数字的格式输出。正确代码如下~
1 2 9 10 25 26 49 50 81 82
4 3 8 11 24 27 48 51 80 83
5 6 7 12 23 28 47 52 79 84
16 15 14 13 22 29 46 53 78 85
17 18 19 20 21 30 45 54 77 86
36 35 34 33 32 31 44 55 76 87
37 38 39 40 41 42 43 56 75 88
64 63 62 61 60 59 58 57 74 89
65 66 67 68 69 70 71 72 73 90
100 99 98 97 96 95 94 93 92 91
的数组。
一直保持循环的思维,错将if用while来代替,运行了半天也没发现原因...幸好虹哥帮指正了,还有数字的格式输出。正确代码如下~
public class PrintArray {
static void initial(int[][] a, int n) {
if (n > 0) {
if (n % 2 == 0) {
int temp = (n - 1) * (n - 1) + 1;
for (int i = 0; i < n; i++) {
a[i][n - 1] = temp++;
}
for (int j = n - 2; j >= 0; j--) {
a[n - 1][j] = temp++;
}
initial(a ,n - 1);
} else {
int temp = (n - 1) * (n - 1) + 1;
for (int i = 0; i < n; i++) {
a[n - 1][i] = temp++;
}
for (int j = n - 2; j >= 0; j--) {
a[j][n - 1] = temp++;
}
initial(a ,n - 1);
}
}
}
static void print(int[][] a, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%03d", a[i][j]);//System.out.printf("%3d", a[i][j])
System.out.print(" ");
}
System.out.println("");
}
}
public static void main(String[] args) {
int n=10;
int [][] a=new int[n][n];
initial(a,n);
print (a,a.length);
}
}