@Test public void virtualMain() { int[][] matrix = generateMatrix(9); MyArray.printSquareArray(matrix, 2); } public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int square = n * n, i = (int) Math.ceil(n / 2.00); int row = 0, column = 0; int counter = 1; int layer = 0; while (layer < i) { int starter = n - layer * 2; for (int j = counter, len = starter + counter - 1; j <= len; j++) { res[column][row++] = counter++; } row--; column++; for (int j = counter, len = starter + counter - 2; j <= len; j++) { res[column++][row] = counter++; } column--; row--; for (int j = counter, len = starter + counter - 1; j < len; j++) { res[column][row--] = counter++; } row++; column--; for (int j = counter, len = starter + counter - 2; j < len; j++) { res[column--][row] = counter++; } row++; column++; layer++; } return res; }
//辅助打印 /** * format with output * @param data two dimension array * @param unitLen the maximum value of data unit length */ public static void printSquareArray(int[][] data,int unitLen){ unitLen+=1; for (int i = 0; i < data.length; i++) { for (int j = 0,len=data[0].length; j < len; j++) { System.out.print(data[i][j]); int unit = String.valueOf(data[i][j]).length(); printSpace(unitLen - unit); } System.out.println(""); } } private static void printSpace(int num){ while (num-- > 0) System.out.print(" "); }
标签:unitLen,layer,Java,int,矩阵,System,length,旋螺,data From: https://www.cnblogs.com/laremehpe/p/17565393.html