算法设计与分析-棋盘覆盖
- 题目描述
在一个2^k * 2^k个方格组成的棋盘中,恰有一个方格与其他方格不同,称该方格为一特殊方格。现在用 L型(占3小格)骨牌覆盖棋盘上除了特殊方格的所有方格,各骨牌不能重叠。 程序为:将棋盘一分为四,依次处理左上角,右上角,左下角,右下角,递归进行。严格按照这个顺序处理
Input
输入三个数k,x,y,分别表示棋盘大小,特殊方格位置
Outout
共2k行,每行2k个数,每辆个数中间空格隔开 输出按照上述顺序所覆盖的棋盘 特殊方格用0表示,其他为骨牌编号
Sample2 2 2
2 2 3 3
2 0 1 3
4 1 1 5
4 4 5 5
- 代码
include<iostream>
#include<vector>
#include<cmath>
using namespace std;
void dfs(vector<vector<int>>& chessboard, int tx, int ty, int x, int y, int size, int num) {
if (size == 1)
return;
size >>= 1;
int n = (size * size - 1) / 3;
if (x < tx + size && y < ty + size) {
dfs(chessboard, tx, ty, x, y, size, num + 1);
}
else {
chessboard[tx + size - 1][ty + size - 1] = num;
dfs(chessboard, tx, ty, tx + size - 1, ty + size - 1, size, num + 1);
}
if (x < tx + size && y >= ty + size) {
dfs(chessboard, tx, ty + size, x, y, size, num + n + 1);
}
else {
chessboard[tx + size - 1][ty + size] = num;
dfs(chessboard, tx, ty + size, tx + size - 1, ty + size, size, num + n + 1);
}
if (x >= tx + size && y < ty + size) {
dfs(chessboard, tx + size, ty, x, y, size, num + 2 * n + 1);
}
else {
chessboard[tx + size][ty + size - 1] = num;
dfs(chessboard, tx + size, ty, tx + size, ty + size - 1, size, num + 2 * n + 1);
}
if (x >= tx + size && y >= ty + size) {
dfs(chessboard, tx + size, ty + size, x, y, size, num + 3 * n + 1);
}
else {
chessboard[tx + size][ty + size] = num;
dfs(chessboard, tx + size, ty + size, tx + size, ty + size, size, num + 3 * n + 1);
}
return;
}
int main() {
int k, x, y;
cin >> k >> x >> y;
int n = pow(2, k);
vector<vector<int>> chessboard(n);
for (int i = 0; i < n; ++i) {
chessboard[i].resize(n);
}
dfs(chessboard, 0, 0, x - 1 , y - 1, n, 1);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cout << chessboard[i][j] << " ";
}
cout << endl;
}
return 0;
}