分治法(02组合问题)棋盘覆盖问题

棋盘覆盖问题
1.代码

#include<iostream>
#include<windows.h>
#include<iomanip>  
//setw(n)是c++中在输出操作中使用的字段宽度设置,n表示字段宽度。
using namespace std;

int matrix[100][100];
int num = 0;
void chessBoard(int x, int y, int a, int b, int length);

int main()
{
	int a, b, length;
	cout << "请输入棋盘的行列号";
	cin >> length;
	cout << "请输入特殊方格的行列号";
	cin >> a >> b;
	matrix[a][b] = 0;

	chessBoard(1, 1, a, b, length);

	for (int i = 1; i <= length; i++){
		for (int j = 1; j <= length; j++){
			cout << setw(4) << matrix[i][j];
		}
		cout << endl;
	}
	Sleep(50000);

	return 0;
}
void chessBoard(int x, int y, int a, int b, int length) {
	//如果棋盘上只有一个方格,且该方格为一特殊方格
	if (length == 1){  
		return;
	}
	int h = length / 2;   //分割棋盘
	int t = ++num;        //L型骨牌号(从1开始)
	/*左上角*/
	if (a < x + h && b < y + h){   //特殊方格在此棋盘中则划分
		chessBoard(x, y, a, b, h);   
	}else{   //否则先覆盖右下角的方格(用t号L型骨牌),再划分
		matrix[x + h - 1][y + h - 1] = t;
		chessBoard(x, y, x + h - 1, y + h- 1, h);
	}
	/*右上角*/
	if (a < x + h && b >= y + h){  //特殊方格在此棋盘中则划分
		chessBoard(x, y + h, a, b, h);
	}else{   //否则先覆盖左下角的方格(用t号L型骨牌),再划分
		matrix[x + h - 1][y + h] = t;
		chessBoard(x, y + h, x + h - 1, y + h, h);
	}
	/*右下角*/
	if (a >= x + h && b >= y + h){  //特殊方格在此棋盘中则划分
		chessBoard(x + h, y + h, a, b, h);
	}else{   //否则先覆盖左上角的方格(用t号L型骨牌),再划分
		matrix[x + h][y + h] = t;
		chessBoard(x + h, y + h, x + h, y + h, h);
	}
	/*左下角*/
	if (a >= x + h && b < y + h){  //特殊方格在此棋盘中则划分
		chessBoard(x + h, y, a, b, h);
	}else{   //否则先覆盖右上角的方格(用t号L型骨牌),再划分
		matrix[x + h][y + h - 1] = t;
		chessBoard(x + h, y, x + h, y + h - 1, h);
	}
}

2.结果示例
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值