分治法:棋盘覆盖

分治法:棋盘覆盖

关于具体的实现过程就不累牍了 ,这里给出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 )和开始时被覆盖的那个点就可以生成结果,使用图形显示,如下图:
分治法:棋盘覆盖_第1张图片
分治法:棋盘覆盖_第2张图片

源码我已经放在github上了 :

https://github.com/cassiePython/BoardCover

你可能感兴趣的:(算法,二分搜索,棋盘覆盖)