两个皇后都不能处于同一行、同一列或同一斜线上
讨论如果是八个皇后,即存在于8*8的行列式中,每行每列一定存在一个皇后,现在我们用queen[row]=col 表示在第row行的皇后处于第col列,
位置的选定,5人 然后判断此时皇后所处的位置是否发生冲突,如果没有冲突且没有超过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");//每执行一行换行
}
}
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);//执行放置皇后
return 0;
}