笔者用栈的数据结构实现了八皇后问题,这种方法相对比较简单,但是别的方法也可以解出来,这段代码还有很多地方可以优化,有兴趣的读者可以深入研究。
#include<iostream>
#include<vector>
using namespace std;
template<typename T>
class stack
{
public:
stack() { cur = 0; };
~stack() {};
T pop();
void traverse();
void push(T data);
int empty();
T operator[](const int n) { return head[cur-n-1]; }
public:
vector<T>head;
int cur;
};
template<typename T>
T stack<T>::pop()
{
if (head.size() == 0)
{
cout << "stack is empty" << endl;
return 0;
}
else
{
T temp;
cur--;
temp = head.back();
head.pop_back();
return temp;
//head.emplace_back(); 直接构造一个元素在尾部
}
}
template<typename T>
void stack<T>::traverse()
{
for (int i = cur - 1; i >= 0; i--)
{
cout << head[i] << endl;
}
}
template<typename T>
void stack<T>::push(T data)
{
head.push_back(data);
cur++;
}
template<typename T>
int stack<T>::empty()
{
return head.size();
}
struct Queen
{
int x, y;
Queen(int xx = 0, int yy = 0) :x(xx), y(yy) {};
bool operator==(Queen const &q) const
{
return (x == q.x) ||
(y == q.y) ||
(x + y == q.x + q.y) ||
(x - y == q.x - q.y);
}
bool operator!=(Queen const &q) const { return !(*this == q); }
};
class play
{
public:
play(int data);
~play() {};
void playChess();
int judgeChessboard(const Queen &q);
public:
stack<Queen>solu;
int curr;
int n;
int **array;
};
play::play(int data)
{
curr = 0;
n = data;
array = new int *[n];
for (int i = 0; i < n; i++)
{
array[i] = new int[n];
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
array[i][j] = 1;
}
}
}
void play::playChess()
{
Queen q(0, 0);
solu.push(q);
/*do
{
if (q.x>n)
{
solu.pop();
curr--;
q.x = 0;
}
else
{
q.y++;
for (int i = 0; i <= n; i++)
{
if (q!=solu[curr])
{
q.x++;
}
else
{
curr++;
}
}
}
} while ((q.x < n) && (q.x >= 0) && (q.y < n) && (q.y >= 0));*/
//q.y++;
//do
//{
// if (judgeChessboard(q))
// {
// solu.push(q);
// q.x++;
// q.y++;
// }
// else
// {
// if (q.x<n)
// {
// //先修改栈顶的X值
// q = solu[0];
// q.x++;
// if (judgeChessboard(q))
// {
// solu.pop();
// solu.push(q);
// }
// }
// else
// {
// solu.pop();
// q = solu[0];
// q.x++;
// }
// }
//} while (solu.empty() <= n);
//for (int i = 0; i < solu.empty(); i++)
//{
// cout << solu[i].x << endl;
//}
do
{
if (n <= solu.empty() || n <= q.x)
{ //已经出界 出栈并试探下一列
q = solu.pop();
q.x++;
}
else
{
while ((q.x<n)&&(judgeChessboard(q) > 0)) //等于0 则说明可以匹配
{
q.x++;
}
if (n>q.x)
{
solu.push(q);
q.y++;
q.x = 0;
}
}
} while (q.y<n);
for (int i = 0; i < solu.empty(); i++)
{
cout << solu[i].x << endl;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (j==solu[i].x)
{
cout << "O";
}
else
{
cout << "X";
}
}
cout << endl;
}
}
int play::judgeChessboard(const Queen &q)
{
int temp = 0;
for (int i = 0; i < solu.empty(); i++)
{
if (q!=solu[i])
{
temp += 0;
}
else
{
temp += 1;
}
}
return temp;
}
int main()
{
play p(4);
p.playChess();
return 0;
}
当输入为4时结果为
2
0
3
1
XXOX
OXXX
XXXO
XOXX
其中O代表皇后的位置。
如有不好的地方欢迎大家批评指正。欢迎大家一起交流。