算法设计与分析递归分治经典问题-棋盘覆盖

算法设计与分析-棋盘覆盖

  1. 题目描述
    在一个2^k * 2^k个方格组成的棋盘中,恰有一个方格与其他方格不同,称该方格为一特殊方格。现在用 L型(占3小格)骨牌覆盖棋盘上除了特殊方格的所有方格,各骨牌不能重叠。 程序为:将棋盘一分为四,依次处理左上角,右上角,左下角,右下角,递归进行。严格按照这个顺序处理
    Input
    输入三个数k,x,y,分别表示棋盘大小,特殊方格位置
    Outout
    共2k行,每行2k个数,每辆个数中间空格隔开 输出按照上述顺序所覆盖的棋盘 特殊方格用0表示,其他为骨牌编号
    Sample
    2 2 2
    
    2 2 3 3
    2 0 1 3
    4 1 1 5
    4 4 5 5
    
  2. 代码
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() {
	//棋盘大小2^k × 2^k, 缺失方格坐标(x, y)
	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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值