- public class Test9 {
- public static void main(String[] args) {
- int[][] matrix = new int[8][8];
- aRound(matrix, matrix.length, 0, 1);
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix.length; j++) {
- System.out.print(matrix[i][j] + "\t");
- }
- System.out.println();
- System.out.println();
- }
- }
- /**
- * @param matrix
- * 矩阵
- * @param size
- * 规模
- * @param time
- * 递归次数
- * @param startNum
- * 赋值 初值
- */
- private static void aRound(int[][] matrix, int size, int time, int startNum) {
- // TODO Auto-generated method stub
- if (size > 0) {
- if (size == 1) {
- matrix[matrix.length / 2][matrix.length / 2] = startNum;// 打印中心点
- } else {
- int row = time;// 行坐标与递归次数相同
- int colum = time;// 列坐标与递归次数相同
- int counter = size * size - (size - 2) * (size - 2);// 设置当前递归赋值一圈的赋值次数的计数器,正好是矩阵掏出“空心”
- for (int i = 0; i < counter; i++) {
- if (i < size - 1) {
- // 方向向右,行不变,列增加
- matrix[row][colum++] = startNum++;
- } else if (i < 2 * (size - 1)) {
- // 方向向下,行数递加,列数不变
- matrix[row++][colum] = startNum++;
- } else if (i < 3 * (size - 1)) {
- // 方向向左,行数不变,列数递减
- matrix[row][colum--] = startNum++;
- } else {
- // 方向向上,行递减,列不变
- matrix[row--][colum] = startNum++;
- }
- }
- time++;
- // 每次递归规模矩阵规模减2
- size = size - 2;
- // 递归
- aRound(matrix, size, time, startNum);
- }
- }
- }
- }
复制代码
|
|