实现分治法求解棋盘覆盖问题

#include <iostream>
#include <time.h>
#include <algorithm>
#include <iomanip>
int **chess;
using namespace std;
int flag = 1;
void Init_Chess(int x)//初始化数组
{
    chess = new int*[x + 2];
    for(int i = 0; i < x + 2; i++)
    {
        chess[i] = new int[x + 2];
        for(int j = 0; j < x + 2; j++)
            chess[i][j] = -1;
    }
}
void ChessBoard(int lu, int rd, int dx, int dy, int size)//完成棋盘覆盖
{
    size = size / 2;//减小规模
    if(size == 0)
        return;
    int number = flag;
    flag++;
    if(dx < lu + size && dy <= rd - size)//填充左上角
    {
        ChessBoard(lu, rd - size, dx, dy, size);//如果有标记则调用
    } else
    {
        chess[rd - size][lu + size - 1] = number;//填充左下角的代码
        ChessBoard(lu, rd - size, lu + size - 1, rd - size, size);
    }
    if(dx >= lu + size && dy <= rd - size)//填充右上角
    {
        ChessBoard(lu + size, rd - size, dx, dy, size);
    } else
    {
        chess[rd - size][lu + size] = number;
        ChessBoard(lu + size, rd - size, lu + size, rd - size, size);
    }
    if(dx < lu + size && dy > rd - size)//填充左下角
    {
        ChessBoard(lu, rd, dx, dy, size);
    } else
    {
        chess[rd - size + 1][lu + size - 1] = number;
        ChessBoard(lu, rd, lu + size - 1,rd - size + 1, size);
    }
    if(dx >= lu + size && dy > rd - size)//填充右下角
    {
        ChessBoard(lu + size, rd, dx, dy, size);
    } else
    {
        chess[rd - size + 1][lu + size] = number;
        ChessBoard(lu + size, rd, lu + size, rd - size + 1, size);
    }
    return;
}
int main()
{
    int length;
    int x, y;
    cout << "矩阵大小:" << endl;
    cin >> length;
    cout << "填充位置:" << endl;
    cin >> x >> y;
    int L = pow(2, length);
    Init_Chess(L);
    chess[y][x] = 0;
    /*for(int i = 1; i < L + 1; i++)
    {
        for(int j = 1; j < L + 1; j++)
            cout << setiosflags(ios::right) << setw(3) << chess[i][j];
        cout << endl;
    }*/
    cout << "-------------------" << endl;
    ChessBoard(1 ,L, x, y, L);
    for(int i = 1; i < L + 1; i++)
    {
        for(int j = 1; j < L + 1; j++)
            cout << setiosflags(ios::right) << setw(4) << chess[i][j];
        cout << endl;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值