#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;
}
}
实现分治法求解棋盘覆盖问题
最新推荐文章于 2021-11-17 22:48:55 发布