写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。如: n = 4 则打印:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
直接调用show3(4); 即可,功能都在show2中
- public static void show3(int n)
- {
- int[][] array = new int[n][n];
- int number = 1;
- int time = n/2;
- show2(array, 0, n, number, time);
-
- if(n%2 == 1)
- {
- array[n/2][n/2] = n*n;
- }
-
- for(int i=0; i<n; ++i)
- {
- for(int j=0; j<n; ++j)
- {
- System.out.print(array[i][j]+ "\t");
- }
- System.out.println();
- }
- }
- public static void show2(int[][] array, int start, int end, int number, int times)
- {
-
- for(int i=start; i<end-1; ++i)
- {
- array[start][i] = number++;
- }
- for(int i=start; i<end-1; ++i)
- {
- array[i][end-1] = number++;
- }
- for(int i=end-1; i>start; --i)
- {
- array[end-1][i] = number++;
- }
- for(int i=end-1; i>start; --i)
- {
- array[i][start] = number++;
- }
- if(times>1)
- {
- show2(array, start+1, end-1, number, times-1);
- }
- }
复制代码
|
|