#include <iostream> using namespace std; class ChessBoard { private: int board[50][50];//记录骨牌序号 int dr;//初始棋盘暗格横坐标 int dc;//初始棋盘暗格纵坐标 int size;//初始化棋盘长度 int count; public: //构造函数,初始化棋盘 ChessBoard(int darkRow,int darkCol,int size) { this->dr=darkRow; this->dc=darkCol; this->size=size; this->count=100;//方便打印效果,设置骨牌号为3位数 board[darkRow][darkCol]=999;//最初棋盘阴影设为999号骨牌 } //分治核心算法 void chessBoard(int topRow,int topCol,int darkRow,int darkCol,int localSize) { if(localSize==1)//如果只剩下一个方格,则它一定已经被覆盖过 { return; } int temp=count++; localSize=localSize/2; //阴影位于左上角 if(darkRow<topRow+localSize&&darkCol<topCol+localSize) { chessBoard(topRow,topCol,darkRow,darkCol,localSize); } else { board[topRow+localSize-1][topCol+localSize-1]=temp; chessBoard(topRow,topCol,topRow+localSize-1,topCol+localSize-1,localSize); } //阴影位于右上角 if(darkRow<topRow+localSize&&darkCol>=topCol+localSize) { chessBoard(topRow,topCol+localSize,darkRow,darkCol,localSize); } else { board[topRow+localSize-1][topCol+localSize]=temp; chessBoard(topRow,topCol+localSize,topRow+localSize-1,topCol+localSize,localSize); } //阴影位于左下角 if(darkRow>=topRow+localSize&&darkCol<topCol+localSize) { chessBoard(topRow+localSize,topCol,darkRow,darkCol,localSize); } else { board[topRow+localSize][topCol+localSize-1]=temp; chessBoard(topRow+localSize,topCol,topRow+localSize,topCol+localSize-1,localSize); } //阴影位于右下角 if(darkRow>=topRow+localSize&&darkCol>=topCol+localSize) { chessBoard(topRow+localSize,topCol+localSize,darkRow,darkCol,localSize); } else { board[topRow+localSize][topCol+localSize]=temp; chessBoard(topRow+localSize,topCol+localSize,topRow+localSize,topCol+localSize,localSize); } } //解决骨牌问题 void chessSolve() { chessBoard(1,1,dr,dc,size); } //打印覆盖结果 void display() { for(int i=1;i<=size;i++) { for(int j=1;j<=size;j++) { cout<<(char)board[i][j]<<" "; } cout<<endl; } } }; void main() { ChessBoard test(3,3,8);// 棋盘大小为2的n次方,否则无解 test.chessSolve();//解决覆盖问题 test.display();//打印结果 }