程序源文件下载地址在文章后面。
---------------------------------------------------------------------
八皇后问题,网上的解法很多,在此我说一下自己的
理解,权当是学习笔记了。
注:四皇后解法总共有2种,八皇后解法总共有92种,16皇后有很多种解法,我运行程序几分钟结果都没出来。
-------------------------------------------------------------------------------------------------------------------------------------------------
解题思路:跟穷举查不多,我们依次在每一行放一个皇后,而一行有八列,所以我们在放置一个皇后时,就要
马上判断皇后放置的列是否符合条件,如果符合,我们就放置下一个皇后,如果不符合,我们就尝试着将皇后
放置在下一列,接着像刚才一样判断皇后放置的列是否合法...如此循环,直到最后一列为止。
------------------------------------------------------------------------------------------------------------------------------------------------
因为有八列,所以每行皇后的位置就有八种可能,我们在程序中用一个循环来控制即可。
------------------------------------------------------------------------------------------------------------------------------------------------
//程序源码
#include <iostream>
#include <Windows.h>
using namespace std;
#define N 8 //这是解的是8皇后问题,如果要解4、16皇后等,只须将8改掉即可,方便吧。
int queen[N]={0}; //数组queen[N]的下标表示皇后所在的行,queen[N]其值表示皇后所在的列
//判断皇后是否能够放在第row行
bool CanPlace(int row)
{
for(int j=0;j<row;j++)//将第row行皇后与前面所有行的皇后进行比较
{
if (queen[row]==queen[j]||row+queen[row]==j+queen[j]||row-queen[row]==j-queen[j])
return false;//不能放皇后
}
return true; //可以放皇后
}
//输出皇后的位置
void PrintfQueen()
{
for(int i=0;i<N;i++)
{
for (int j=0;j<N;j++)
{
if(queen[i]==j)
cout<<"■ ";//输出皇后
else
cout<<"□ ";
}
cout<<endl;
}
cout<<endl<<endl;
}
int Sum=0;
void Queen(int row)
{
if (row>=N)//皇后已经全部放完时
{
PrintfQueen();//输出皇后的位置
Sum++;
return;
}
else
{
for (int i=0;i<N;i++) //总共有N列,一列一列的试探放置皇后
{
queen[row]=i; //将第row行皇后放在第i列上面
if(CanPlace(row))//判断皇后的位置是否正确
Queen(row+1); //放下一个皇后
}
}
}
void main(void)
{
Queen(0);
cout<<"总的摆法,Sum="<<Sum;
cin.get();
}
--------------------------------------------------------------------------------------------------------------------------------------------------
//效果截图
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
源码下载地址:八皇后问题解法.zip //免积分
备份地址:八皇后问题解法.zip //需积分