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

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;

int tile = 0;

template <class Type>
void Make2DArray(Type** &x, int rows, int cols);
template <class Type>
void Delete2DArray(Type** &x, int rows, int cols);
template <class Type>
void ChessBoard(Type** &x, int tr, int tc, int dr, int dc, int size);

int main()
{
    int k;
    cout<<"请输入K:";
    cin>>k;
    int size = pow(2, k); //2^k
    int** x;
    int dr, dc; //特殊格子坐标
    int i, j;

    Make2DArray(x, size, size);
    do
    {
        cout<<"请输入dr, dc:";
        cin>>dr>>dc;
    }while(dr<1 || dr>size || dc<1 || dc>size);
    x[dr][dc] = 0;
    ChessBoard(x, 1, 1, dr, dc, size);
    cout<<endl;
    for(i = 1; i <= size; i++)
    {
        for(j = 1; j <= size; j++)
        {
            printf("%5d", x[i][j]);
        }
        if(i == size) cout<<endl;
        else cout<<endl<<endl;
    }

    Delete2DArray(x, size, size);

    return 0;
}

template <class Type>
void ChessBoard(Type** &x, int tr, int tc, int dr, int dc, int size)
{
    if(size == 1) return;
    int s = size/2;
    int t = ++tile;

    //左上角
    if(dr<tr+s && dc<tc+s) ChessBoard(x, tr, tc, dr, dc, s);
    else
    {
        x[tr+s-1][tc+s-1] = t;
        ChessBoard(x, tr, tc, tr+s-1, tc+s-1, s);
    }
    //右上角
    if(dr<tr+s && dc>=tc+s) ChessBoard(x, tr, tc+s, dr, dc, s);
    else
    {
        x[tr+s-1][tc+s] = t;
        ChessBoard(x, tr, tc+s, tr+s-1, tc+s, s);
    }
    //左下角
    if(dr>=tr+s && dc<tc+s) ChessBoard(x, tr+s, tc, dr, dc, s);
    else
    {
        x[tr+s][tc+s-1] = t;
        ChessBoard(x, tr+s, tc, tr+s, tc+s-1, s);
    }
    //右下角
    if(dr>=tr+s && dc>=tc+s) ChessBoard(x, tr+s, tc+s, dr, dc, s);
    else
    {
        x[tr+s][tc+s] = t;
        ChessBoard(x, tr+s, tc+s, tr+s, tc+s, s);
    }
}

template <class Type>
void Make2DArray(Type** &x, int rows, int cols)
{
    x = new Type*[rows+1];
    int i;
    for(i = 0; i < rows+1; i++)
    {
        x[i] = new Type[cols+1];
    }
}

template <class Type>
void Delete2DArray(Type** &x, int rows, int cols)
{
    int i;
    for(i = 0; i < rows+1; i++)
    {
        delete []x[i];
    }
    delete []x;
    x = 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值