螺旋矩阵的递归实现

package test;


public class Test {
  public static void main(String[] args) {
	  printMatrix2(5);
  }
  public static void CreateMatrix(int n,int intValue,int circle)
  {
	 if(n<=0) return;
	 for(int i=0;i<n;i++)
	 {
		 if(i==0) for(int j=0;j<n;j++) array[i+circle][j+circle]=intValue+j;
		 if(i!=0&&i!=n-1) {array[circle+i][circle]=intValue+3*(n-1)+n-1-i;
		 array[circle+i][circle+n-1]=intValue+n+i-1;}
		 if(i==n-1) for(int j=0;j<n;j++) array[i+circle][j+circle]=intValue+2*n-2+n-1-j;
	 }
	 CreateMatrix(n-2,intValue+3*(n-1)+n-1,circle+1);
  }
  public static int[][] array;
  public static void printMatrix2(int n)
  {
	  array=new int[n][n];
	  CreateMatrix(n,1,0);
	  for(int i=0;i<n;i++){
	   for(int j=0;j<n;j++)
		   System.out.print(String.format("%5d",array[i][j]));
	   System.out.println();
	  }
  }
}

你可能感兴趣的:(J#)