在8X8的棋盘上放置8个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行,同一列,同一斜线上。用算法打印所有可能的摆放方法。
仅供学习交流使用
#include<iostream>
int sum = 0;//定义全局变量
#define StackSize 8 //定义常量
using namespace std;
class SeqStack
{
public:
SeqStack() { top = -1; }//构造函数
void Push(int x);//入栈
int Pop();//出栈
bool JudgeMent();//判断是否符合条件
void Place(int n);//放置皇后
void Print();//打印
bool Empty() { if (top == -1) return true; else return false; }; //判断栈是否为空
private:
int data[StackSize];
int top;
};
void SeqStack::Push(int x) //入栈
{
if (top >= StackSize - 1) throw "栈上溢";
top++;
data[top] = x;
}
int SeqStack::Pop() //出栈
{
if (Empty()) throw "栈下溢";
top--;
return data[top + 1];
}
bool SeqStack::JudgeMent()
{
for (int i = 0; i < top; i++)
{
if (abs(data[top] - data[i]) == top - i || data[top] == data[i])//判断任意两个皇后是否在同一行、同一列和同一斜线上判断
return false;
}
return true;
}
//采用递归法放置皇后,同时调用判断函数判断是否符合情况
void SeqStack::Place(int n)
{
for (int i = 0; i < StackSize; i++)
{
Push(i);
if (JudgeMent())//判断放置是否合理
{
if (top < StackSize - 1)//避免发生上溢
Place(n + 1);
else
{
sum++;
Print();//棋盘已放置完整,打印在屏幕上
}
}
Pop();
}
}
void SeqStack::Print() //打印操作,用‘O’代替空位,用‘*’代替皇后
{
for (int i = 0; i < StackSize; i++)
{
for (int j = 0; j < StackSize; j++)
{
if (data[i] == j) cout << "* ";
else cout << "O ";
}
cout << endl;
}
cout << endl;
}
int main()//主函数
{
SeqStack queen;
queen.Place(0);
cout << "综上可知,八皇后问题共有 " << sum << " 种摆放方法\n";
return 0;
}