棋盘覆盖问题(递归+分治)

分治,把棋盘分成四块,能分就分,直到最后剩下一块黑的,就返回;
以左上角为例,
如果黑块在左上方,那么就递归;
如果黑块不在左上方,就填充一个L假设是黑块,填充的位置是分块之前的大棋盘的中间,不包含有
黑块的一部分,其余三部分填上L,即让他们等于一个值;然后再递归;

#include<iostream>
using namespace std;

const int maxn = 8;
int tile = 1;
int board[maxn][maxn];

void ChessBoard(int tr, int tc, int dr, int dc, int size)
{
	if(size == 1) return;
	int t = tile++;
	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 print()
{
	cout.setf(ios::left);
	for(int i = 0; i < maxn; i++)
	{
		for(int j = 0; j < maxn; j++)
		{
			cout.width(3);
			cout<<board[i][j];
		}
		cout<<endl;
	}	
}

int main()
{
	ChessBoard(0,0,3,4,maxn);
	print();
	return 0;
}

展开阅读全文

没有更多推荐了,返回首页