【分治算法】一个简单的例子——数字旋转方阵Java版本

分治算法的思想分为三个阶段:

1. 划分

2. 求解子问题

3. 合并

 

public class B {
    final static int N = 6;
    static int[][] data = new int[N][N];

    public static void main(String[] args) {
        full(1, 0, 6);
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[i].length; j++) {
                System.out.print(data[i][j] + "\t");
            }
            System.out.println();
        }
    }

    static void full(int number, int begin, int size) {
        int i, j, k;
        if (size == 0)
            return;
        if (size == 1){
            data[begin][begin] = number;
            return;
        }
        i = begin; j = begin;
        for (k = 0; k < size-1; k++) {
            data[i][j] = number;
            number++; i++;
        }
        for (k = 0; k< size-1; k++) {
            data[i][j] = number;
            number++; j++;
        }
        for (k = 0; k < size-1; k++) {
            data[i][j] = number;
            number++; i--;
        }
        for (k = 0; k < size-1; k++) {
            data[i][j] = number;
            number++; j--;
        }
        full(number, begin+1, size-2);
    }

}

结果如下:

 

1    20    19    18    17    16    
2    21    32    31    30    15    
3    22    33    36    29    14    
4    23    34    35    28    13    
5    24    25    26    27    12    
6    7      8     9    10    11    

 

posted @ 2023-09-12 15:47  宝山方圆  阅读(26)  评论(0编辑  收藏  举报