程序代码:
#include <stdio.h>
const int maxn = 2 << 6;
int code_number = 1;
void chessBord(int curx,int cury,int bx,int by,int size);
void print_r(int size);
int map[maxn][maxn];
int main()
{
chessBord(0,0,1,1,4);
print_r(4);
return 0;
}
void print_r(int size){
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
printf("%3d ",map[i][j]);
}
printf("\n");
}
}
void chessBord(int curx,int cury,int bx,int by,int size){//curx,cury为当前方阵左上方坐标,和size可谓一确定一个方阵,bx,by为黑方格所在位置
if(size == 1){
return;
}
int midx = curx + size / 2;
int midy = cury + size / 2;
int some_number = code_number++; //必须再定义一个变量,这是属于同一层的变量值。
if(bx < midx && by < midy){//在左上区域
chessBord(curx,cury,bx,by,size / 2);
}else{//不再该区域,就补上同一个数字,然后继续分解并把补上的也视为黑块
map[midx - 1][midy - 1] = some_number;
chessBord(curx,cury,midx - 1,midy -1,size / 2);
}
if(bx >= midx && by < midy){//在左下区域
chessBord(midx,cury,bx,by,size / 2);
}else{
map[midx][midy - 1] = some_number;
chessBord(midx,cury,midx,midy - 1,size / 2);
}
if(bx < midx && by >= midy){//在右上区域
chessBord(curx,midy,bx,by,size / 2);
}else{
map[midx - 1][midy] = some_number;
chessBord(curx,midy,midx - 1,midy,size/2);
}
if(bx >= midx && by >= midy ){//在右下区域
chessBord(midx,midy,bx,by,size / 2);
}else{
map[midx][midy]= some_number;
chessBord(midx,midy,midx,midy,size/2);
}
}