棋盘覆盖问题

描述:

在一个2^k×2^k 个方格组成的棋盘中,恰有一个方格与其它方格不同,称该方格为一特殊方格,且称该棋盘为一特殊棋盘。在棋盘覆盖问题中,要用图示的4种不同形态的L型骨牌覆盖给定的特殊棋盘上除特殊方格以外的所有方格,且任何2个L型骨牌不得重叠覆盖。 为了使结果统一,我们约定,覆盖时从左上区域开始,按顺时针方向覆盖棋盘。

输入:

输入共一行三个数,第一个数k表示棋盘的规模,第二个数m表示特殊方格的横坐标,第三个数n表示棋盘的纵坐标。开始左上角坐标为(1,1)。正南方为纵坐标正方向,正东方为横坐标正方向。

输出:

输出为一个2^k×2^k的方阵,特殊点为0,其它为覆盖后值,从1开始直到覆盖结束。同一行数据之间以空格隔开,注意每行末尾没有空格。

输入样例:

2 1 2

输出样例:

2 0 3 3
2 2 1 3
4 1 1 5
4 4 5 5

此题的描述有些毛病,题中说输入的第二个和第三个数是特殊方块的横纵坐标,但实际上输入的是行号和列号,恰好坐标相反,只需在程序中调用棋盘覆盖函数时调换x和y的位置即可,源代码如下:

import java.io.*;
import java.util.Arrays;

public class ChessboardCover {
private static int[][] chessboard = null;
private static int count = 0;

public static void main(String[] args) throws Exception {
int k, n; //n为棋盘的长度和宽度
int x, y; //特殊方块儿的坐标
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
br.close();
String[] inputArray = input.split(" ");
k = Integer.parseInt(inputArray[0]);
x = Integer.parseInt(inputArray[1]);
y = Integer.parseInt(inputArray[2]);
n = (int) Math.pow(2, k);
chessboard = new int[n][n];
chessboard[x - 1][y - 1] = 0;
chessboardCoverFunc(1, 1, y, x, n); //y为横坐标,x为总坐标
/*
for (int i = 0; i < n; i++) {
System.out.println(Arrays.toString(chessboard[i]));
}
*/
for (int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(j != n-1){
System.out.print(chessboard[i][j] + " ");
}
else{
System.out.println(chessboard[i][j]);
}
}
}
}

public static void chessboardCoverFunc(int cx, int cy, int x, int y, int n) {
if (n == 1) {
return;
}
int t = ++count;
int size = n / 2;
if (x <= cx + size - 1 && y <= cy + size - 1) {
chessboardCoverFunc(cx, cy, x, y, size);
} else {
chessboard[cy + size - 2][cx + size - 2] = t;
chessboardCoverFunc(cx, cy, cx + size - 1, cy + size - 1, size);
}
if (x >= cx + size && y <= cy + size - 1) {
chessboardCoverFunc(cx + size, cy, x, y, size);
} else {
chessboard[cy + size - 2][cx + size - 1] = t;
chessboardCoverFunc(cx + size, cy, cx + size, cy + size - 1, size);
}
if (x <= cx + size - 1 && y >= cy + size) {
chessboardCoverFunc(cx, cy + size, x, y, size);
} else {
chessboard[cy + size - 1][cx + size - 2] = t;
chessboardCoverFunc(cx, cy + size, cx + size - 1, cy + size, size);
}
if (x >= cx + size && y >= cy + size) {
chessboardCoverFunc(cx + size, cy + size, x, y, size);
} else {
chessboard[cy + size - 1][cx + size - 1] = t;
chessboardCoverFunc(cx + size, cy + size, cx + size, cy + size,
size);
}
}
}







posted @ 2012-04-08 14:08  盖慧彤  阅读(348)  评论(0编辑  收藏  举报