问题: 用4种不同形态的L型骨牌, 覆盖给定特殊棋盘上除特殊方格以外的所有方格,且任何2个不得重叠。
1 : 代码求解
#include
using namespace std;
const int MAX = 100;
int Board[MAX][MAX];
int times = 0;
void OutPut(int size)
{
for(int i = 0; i < size; ++i)
{
for(int j = 0; j < size; ++j)
cout << Board[i][j] << " ";
cout << endl;
}
}
void ChessBoard(int tr, int tc, int dr, int dc, int size)
{
if(size == 1)
return ;
int t = ++times;
int s = size / 2;
if(dr < tr + s && dc < tc + s)
{
ChessBoard(tr, tc, dr, dc, s);
}
else
{
Board[tr + s - 1][tc + s - 1] = t;
ChessBoard(tr, tc, tr + s - 1, tc + s - 1, s);
}
if(dr < tr + s && dc >= tc + s)
{
ChessBoard(tr, tc + s, dr, dc, s);
}
else
{
Board[tr + s - 1][tc + s] = t;
ChessBoard(tr, tc + s, tr + s - 1, tc + s, s);
}
if(dr >= tr + s && dc < tc + s)
{
ChessBoard(tr + s, tc, dr, dc, s);
}
else
{
Board[tr + s][tc + s - 1] = t;
ChessBoard(tr + s, tc, tr + s, tc + s - 1, s);
}
if(dr >= tr + s && dc >= tc + s)
{
ChessBoard(tr + s, tc + s, dr, dc, s);
}
else
{
Board[tr + s][tc + s] = t;
ChessBoard(tr + s, tc + s, tr + s, tc + s, s);
}
}
void InPut(int &dr, int &dc, int &size)
{
scanf("%d %d %d", &dr, &dc, &size);
}
int main()
{
int dr, dc, size;
InPut(dr, dc, size);
memset(Board, 0, sizeof(Board));
ChessBoard(0, 0, dr, dc, size);
OutPut(size);
}
注意:size表示的是边的数量,课本描述为size = 2 ^ k, 棋盘规格为 2 ^ k * 2 ^ k。
程序截图:
2 : 时间复杂度分析
此题中规模为K(大写), 则分解成四个子问题, 即 k(小写) = 4;每个子问题规模为 K - 1, 每个子问题的复杂度为O(1),
下面进行迭代求解:
T(K) = 4T(K - 1) + O(1) K > 0;
= 4(4T(K - 2) + O(1)) + O(1)
= 4 ^ 2 T(K - 2) + 4 ^ 1 O(1) + O(1);
......
= 4 ^ K T(K - K) + 4 ^ (K - 1) + 4 ^ (K - 2) + ... + 1
= 4 ^ K T(0) + 4 ^ (K - 1) + 4 ^ (K - 2) + ... + 1
= O(4 ^ K);