思路一:
public class Main { public static void main(String[] args) throws IOException{ int[][] a = print(8); for(int[] el : a) { for(int e : el) { System.out.printf("%4d", e); } System.out.println(""); } } public static int[][] print(int n) { int[][] array = new int[n][n]; int count = 0; //层数 int f = 0; while(count<n/2) { for(int i=0; i<n-2*count-1; i++) { array[count][count+i] = 1+i+f; //上侧-从左到右 array[count+i][n-count-1] = (1+i+f)+(n-2*count-1); //右侧-从上到下 array[n-count-1][n-1-count-i] = (1+i+f)+2*(n-2*count-1); //下侧-从右到左 array[n-1-count-i][count] = (1+i+f)+3*(n-2*count-1); //左侧-从下到上 } count++; f += 4*(n-2*count+1); } if(n%2==1) { array[n/2][n/2] = (int) Math.pow(n, 2); } return array; } }
思路二:
public static int[][] printMatrix(int n) { int[][] res = new int[n][n]; int left=0; int top=0; int right=n-1; int bottom=n-1; int count = 1; while(left<=right&&top<=bottom) { for(int j=left; j<=right; j++) { res[top][j]=count++; } for(int i=top+1; i<=bottom; i++) { res[i][right]=count++; } if(top!=bottom) { for(int j=right-1; j>=left; j--) { res[bottom][j]=count++; } } if(left!=right) { for(int i=bottom-1; i>top; i--) { res[i][left]=count++; } } left++; top++; right--; bottom--; } return res; }
output:
1 2 3 4 5 6 7 8
28 29 30 31 32 33 34 9
27 48 49 50 51 52 35 10
26 47 60 61 62 53 36 11
25 46 59 64 63 54 37 12
24 45 58 57 56 55 38 13
23 44 43 42 41 40 39 14
22 21 20 19 18 17 16 15
转载请注明出处