棋盘覆盖(分治、递归)

来源:互联网 发布:阿里云控制台 编辑:程序博客网 时间:2024/05/16 05:51

问题描述:对于一个2^k*2^k的棋盘,要选定一个格数为3的L形方块填满,且有一个为特殊方格

解决思想:采用分治的思想,可以将棋盘划分成等四块,因为只有一个特殊方块,所以为了满足子问题与父问题相同,我们选定没有特殊方格的其他三块棋盘最靠近中间的方格,先填数字,然后作为特殊方格递归下去,而特殊方格在方法中不作填数处理,边界条件是方格大小为1.

public class Main {    static int flag = 1;    public static void main(String[] args) {        int[][] map = new int[8][8];        chessBoard(map, 8, 0, 0, 2, 3);        for (int i = 0; i < 8; i++) {            for (int j = 0; j < 8; j++)                System.out.printf("%3d", map[i][j]);            System.out.println();        }    }    public static void chessBoard(int[][] map, int size, int x, int y, int tx, int ty) {        if (size == 1)            return;        else {            int t = flag++; //通过数字标记L型方块            // 左上角            if (tx < x + size / 2 && ty < y + size / 2)                chessBoard(map, size / 2, x, y, tx, ty);            else {                map[x + size / 2 - 1][y + size / 2 - 1] = t;                chessBoard(map, size / 2, x, y, x + size / 2 - 1, y + size / 2 - 1);            }            // 右上角            if (tx < x + size / 2 && ty >= y + size / 2)                chessBoard(map, size / 2, x, y + size / 2, tx, ty);            else {                map[x + size / 2 - 1][y + size / 2] = t;                chessBoard(map, size / 2, x, y + size / 2, x + size / 2 - 1, y + size / 2);            }            // 左下角            if (tx >= x + size / 2 && ty < y + size / 2)                chessBoard(map, size / 2, x + size / 2, y, tx, ty);            else {                map[x + size / 2][y + size / 2 - 1] = t;                chessBoard(map, size / 2, x + size / 2, y, x + size / 2, y + size / 2 - 1);            }            // 右下角            if (tx >= x + size / 2 && ty >= y + size / 2)                chessBoard(map, size / 2, x + size / 2, y + size / 2, tx, ty);            else {                map[x + size / 2][y + size / 2] = t;                chessBoard(map, size / 2, x + size / 2, y + size / 2, x + size / 2, y + size / 2);            }        }    }}/*Output:  3  3  4  4  8  8  9  9  3  2  2  4  8  7  7  9  5  2  6  0 10 10  7 11  5  5  6  6  1 10 11 11 13 13 14  1  1 18 19 19 13 12 14 14 18 18 17 19 15 12 12 16 20 17 17 21 15 15 16 16 20 20 21 21*/

时间复杂度分析:
棋盘为2^k*2^k,所以数据规模的变量为k,每次将棋盘平均分割成4块,即每一块的规模为2^(k-1)*2^(k-1),所以有:
当k=1时,T(k) = O(1)
当k>1时,T(k) = 4T(k-1)+O(1)
解得T(k) = 4^k

1 0
原创粉丝点击