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

 

#include<iostream>
using namespace std;
int Board[4][4] = {0};
int tile = 1;
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-1,tc+s,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,tr+s,tc+s,s);
	}
}

void main()
{
	cout<<"覆盖前,棋盘状态:"<<endl;
	for(int i = 0;i < 4;i++)
	{
		for(int j = 0;j < 4;j++)
			cout<<Board[i][j]<<" ";
		cout<<endl;
	} 
	cout<<endl<<"覆盖后,棋盘状态:"<<endl;
	ChessBoard(0,0,2,3,4);
	for(i = 0;i < 4;i++)
	{
		for(int j = 0;j < 4;j++)
			cout<<Board[i][j]<<" ";
		cout<<endl;
	} 
}

/*
覆盖前,棋盘状态:
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

覆盖后,棋盘状态:
2 2 3 3
2 1 1 3
4 1 5 0
4 4 5 5
*/

 

    原文作者:递归与分治算法
    原文地址: https://blog.csdn.net/themagickeyjianan/article/details/8869688
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞