兩個皇后都不能處于同一行、同一列或同一斜線上 討論如果是八個皇后,即存在于8*8的行列式中,每行每列一定存在一個皇后,現在我們用queen[row]=col 表示在第row行的皇后處于第col列,位置的選定,5人 然后判斷此時皇后所處的位置是否發(fā)生沖突,如果沒有沖突且沒有超過row即進行下一行的判斷(遞歸的形式)void EightQueen::putQueen(int QueenAry[],int nRow,int &soulation)//放置皇后{ for (int col = 0; col < QueenCount; col++) { QueenAry[nRow] = col;//當前行的皇后所在列 if (!IsCash(QueenAry, nRow)) {//沒有沖突 if (nRow == QueenCount - 1)//下標為7全部8行解析完畢 { soulation++;//每滿足一次計算器加1 showQueen(QueenAry, QueenCount, soulation);//顯示結果 _getch(); } else { putQueen(QueenAry, nRow + 1, soulation);//下一行的皇后位置 } } } }沖突的判斷斜45度角判斷列判斷bool EightQueen::IsCash(int QueenAry[],int nRow)//是否沖突{ for (int nCol = 0; nCol < nRow; nCol++)//從第0列到第nRow-1列開始判斷 {//有沖突 if (QueenAry[nCol] == QueenAry[nRow])//----------------------------檢測是否在同一列 return true; if (abs(QueenAry[nCol] - QueenAry[nRow]) == abs(nRow - nCol))//----是否在一條斜線上 return true; } return false;// -------沒有沖突}完整代碼#include<iostream>#include<conio.h>using namespace std;#define QueenCount 11//宏定義皇后的數量 10---724 11---2680 class EightQueen//八皇后類的定義{public: void putQueen(int QueenAry[], int nRow, int &soulation);//放置皇后 QueenAry[]用于記錄皇后的 void showQueen(int QueenAry[],int len,int &soulation);//每種方案的展示圖PRivate: bool IsCash(int QueenAry[], int nRow);//沖突判斷};void EightQueen::showQueen(int QueenAry[], int len, int &soulation){ printf("---------Queen position:soulation %d------------------/n", soulation); for (int i = 0; i < len; i++) { /*if (QueenAry[i] == -1) { for (int j = 0; j < len; j++) { printf("%c", 48); } printf("/n"); continue; }*/ //----------------------這段可以省略,可寫可不寫都可以 for (int j = 0; j < QueenAry[i]; j++) printf("%c", 48);//打印皇后之前的 空格為0 皇后為1 printf("%c", 49);//打印皇后 for (int j = 0; j < len - 1 - QueenAry[i]; j++) printf("%c", 48); printf("/n");//每執(zhí)行一行換行 }}bool EightQueen::IsCash(int QueenAry[],int nRow)//是否沖突{ for (int nCol = 0; nCol < nRow; nCol++)//從第0列到第nRow-1列開始判斷 {//有沖突 if (QueenAry[nCol] == QueenAry[nRow])//----------------------------檢測是否在同一列 return true; if (abs(QueenAry[nCol] - QueenAry[nRow]) == abs(nRow - nCol))//----是否在一條斜線上 return true; } return false;// -------沒有沖突}void EightQueen::putQueen(int QueenAry[],int nRow,int &soulation)//放置皇后{ for (int col = 0; col < QueenCount; col++) { QueenAry[nRow] = col;//當前行的皇后所在列 if (!IsCash(QueenAry, nRow)) {//沒有沖突 if (nRow == QueenCount - 1)//下標為7全部8行解析完畢 { soulation++;//每滿足一次計算器加1 showQueen(QueenAry, QueenCount, soulation);//顯示結果 _getch(); } else { putQueen(QueenAry, nRow + 1, soulation);//下一行的皇后位置 } } } }int main(){ int QueenAry[QueenCount];//皇后的數量-----第一行放置第一個數據......第八行放置第八個數據 EightQueen q;//聲明一個變量 int soulation = 0;//計算器清零 q.putQueen(QueenAry, 0, soulation);//執(zhí)行放置皇后 return 0;}
新聞熱點
疑難解答