- /*
- 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
- */
- class JuZhen{
- public static void main(String [] args)
- {
- int n =5;
- int [][] data = new int [n][n];
- int num = 1;
- int size = data.length;
- int begin = 0;
- new JuZhen().print(data , num , begin , size);
-
- for(int i = 0; i < n ; i++)
- {
- for( int j = 0 ; j< n ;j++)
- {
- System.out.print(data[i][j] + "\t");
- }
- System.out.println();
- }
-
- }
-
- void print(int [][] data , int num ,int begin ,int size)
- {
- int col , row;
- if(size==0)//偶数阶矩阵递归入口;
- {
- return;
- }
- if(size==1)//奇数阶矩阵递归入口;
- {
- data[begin][begin] = num;
- return;
- }
-
- col = begin ; row = begin;
-
- for(int k = 0 ; k < size-1 ; k++ )
- {
- data[row][col]=num;
- col++;
- num++;
- }
-
- for(int k = 0 ; k < size-1 ; k++ )
- {
- data[row][col]=num;
- row++;
- num++;
- }
-
- for(int k = 0 ; k < size-1 ; k++ )
- {
- data[row][col]=num;
- col--;
- num++;
- }
-
- for(int k = 0 ; k < size-1 ; k++ )
- {
- data[row][col]=num;
- row--;
- num++;
- }
-
- print(data , num , begin+1 , size - 2);//每调用一次,起始位置每减一圈加1,数组维度会减2;
- }
-
- }
复制代码 |
|