题目描述:
使用分治法求解棋盘覆盖问题。
棋盘覆盖问题的描述:
残缺位置所在的四种不同情况:
/**
* 二分法不相似情况:残缺棋盘
* by
* 小俱的一步步
*/
public class CanquedeQP {
private int size;
private int[][] board;
//所使用三格板的数目
private int amount;
/**
* 初始化board
* @param size 行、列的长度
*/
public CanquedeQP(int size){
this.amount = 0;
this.size = size;
this.board = new int[this.size][this.size];
}
public static void main(String[] args) {
CanquedeQP canquedeQP = new CanquedeQP(16);
canquedeQP.cover(16,0,0,5,8);
System.out.println(canquedeQP);
}
/**
* 分治覆盖法
* @param size 方形棋盘的长宽
* @param tr 子棋盘左上角方格所在行
* @param tc 子棋盘左上角方格所在列
* @param dr 残缺方格所在行
* @param dc 残缺方格所在列
*/
public void cover(int size,int tr,int tc,int dr,int dc){
//当分隔为一个方块时,返回
if (size==1){
return;
}
this.amount++;
int t = this.amount;
size = size/2;
//左上
if (dr<(tr+size) && dc<(tc+size)){
cover(size,tr,tc,dr,dc);
board[tr+size-1][tc+size] = t;
board[tr+size][tc+size-1] = t;
board[tr+size][tc+size] = t;
//覆盖其余部分
cover(size,tr,tc+size,tr+size-1,tc+size);
cover(size,tr+size,tc,tr+size,tc+size-1);
cover(size,tr+size,tc+size,tr+size,tc+size);
//右上
}else if (dr<(tr+size)&& dc>=(tc+size)){
cover(size,tr,tc+size,dr,dc);
board[tr+size-1][tc+size-1] = t;
board[tr+size][tc+size-1] = t;
board[tr+size][tc+size] = t;
//覆盖其余部分
cover(size,tr,tc,tr+size-1,tc+size-1);
cover(size,tr+size,tc,tr+size,tc+size-1);
cover(size,tr+size,tc+size,tr+size,tc+size);
//左下
}else if (dr>=(tr+size) && dc<(tc+size)) {
cover(size, tr + size, tc, dr, dc);
board[tr + size - 1][tc + size - 1] = t;
board[tr + size - 1][tc +size] = t;
board[tr + size][tc + size] = t;
//覆盖其余部分
cover(size, tr, tc, tr + size - 1, tc +size - 1);
cover(size, tr, tc + size, tr + size - 1, tc +size);
cover(size, tr + size, tc + size, tr +size, tc + size);
//右下
}else if (dr>=(tr+size) && dc>=(tc+size)) {
cover(size, tr+size, tc + size, dr, dc);
board[tr + size - 1][tc + size - 1] = t;
board[tr + size-1][tc + size] = t;
board[tr + size][tc + size-1] = t;
//覆盖其余部分
cover(size, tr, tc, tr + size - 1, tc + size - 1);
cover(size, tr , tc+size, tr + size-1, tc + size );
cover(size, tr + size, tc , tr + size, tc + size-1);
}
}
@Override
public String toString() {
String res = "";
for (int i = 0; i < this.size ; i++) {
for (int j = 0; j
测试为16*16的方格残缺位置为【5,8】,输出结果为: