分治法:棋盘覆盖

分治法:棋盘覆盖

关于具体的实现过程就不累牍了 ,这里给出java的实现方法。
/**
	 * 核心算法 :递归调用实现棋盘覆盖
	 * @param stx 覆盖的矩阵的开始的横坐标
	 * @param sty 覆盖的矩阵的开始的纵坐标
	 * @param bx 开始时被覆盖的点的横坐标
	 * @param by 开始时被覆盖的点的纵坐标
	 * @param size 矩形的长度n(2的n次方的n的值)
	 */
	private void ChessBoard(int stx,int sty,int bx,int by,int size)
	{
			if(size==1)
				return;
			int s = size/2;
			if(bx<stx+s){
				if(by<sty+s){
					a[stx+s][sty+s-1]=a[stx+s-1][sty+s]=a[stx+s][sty+s]=marker++;
					ChessBoard(stx, sty,bx, by, s);//覆盖最上角
					
					ChessBoard(stx, sty+s,stx+s-1,sty+s, s);//覆盖右上角
		
					ChessBoard(stx+s, sty, stx+s, sty+s-1, s);//覆盖左下角
				
					ChessBoard(stx+s, sty+s, stx+s, sty+s, s);//覆盖右下角
				}
				else{
					
					a[stx+s-1][sty+s-1] = a[stx+s][sty+s-1] = a[stx+s][sty+s] = marker++;
					ChessBoard(stx, sty, stx+s-1, sty+s-1, s);//覆盖最上角
					ChessBoard(stx, sty+s,bx, by, s);//覆盖右上角
					ChessBoard(stx+s, sty, stx+s, sty+s-1, s);//覆盖左下角
					ChessBoard(stx+s, sty+s, stx+s, sty+s, s);//覆盖最下角
				}
			}else{
				if(by<sty+s){
					a[stx+s-1][sty+s-1]=a[stx+s-1][sty+s]=a[stx+s][sty+s]=marker++;
					ChessBoard(stx, sty,stx+s-1, sty+s-1, s);//覆盖最上角
					ChessBoard(stx, sty+s,stx+s-1,sty+s, s);//覆盖右上角
					ChessBoard(stx+s, sty,bx, by, s);//覆盖左下角
					ChessBoard(stx+s, sty+s, stx+s, sty+s, s);//覆盖最下角
				}
				else{
					a[stx+s-1][sty+s-1] = a[stx+s-1][sty+s] = a[stx+s][sty+s-1] = marker++;
					ChessBoard(stx, sty, stx+s-1, sty+s-1, s);//覆盖最上角
					ChessBoard(stx, sty+s,sty+s-1, sty+s, s);//覆盖右上角
					ChessBoard(stx+s, sty, stx+s, sty+s-1, s);//覆盖左下角
					ChessBoard(stx+s, sty+s,bx, by, s);//覆盖最下角
				}
			}
	}

最后我做了一个简单的android的demo用于显示棋盘覆盖:

通过输入大小(size )和开始时被覆盖的那个点就可以生成结果,使用图形显示,如下图:



源码我已经放在github上了 :

https://github.com/cassiePython/BoardCover

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值