#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
struct Queen
{
int x;
int y;
};
typedef struct SeqStack
{
Queen* Base;
Queen* Top;
int stacksize;
};
void InitStack(SeqStack& S,int N)
{
S.Base = new Queen[N+1];
if (!S.Base) exit(0);
S.Top = S.Base;
S.stacksize = N+1;
}
bool Check(SeqStack S,Queen *Q)
{
Queen* p;
p = S.Base;
while (p < S.Top)
{
if (Q->x - p->x == abs(Q->y - p->y) || Q->y == p->y)
{
return false;
break;
}
p++;
}
return true;
}
void StackTraverse(SeqStack S)
{
Queen* p;
p = S.Base;
while (p < S.Top)
{
cout << p->x << " " << p->y << endl;
p++;
}
cout << endl;
}
void Push(SeqStack& S, Queen* Q)
{
S.Top->x = Q->x;
S.Top->y = Q->y;
S.Top++;
}
void Pop(SeqStack& S, Queen*& Q)
{
--S.Top;
Q->x = S.Top->x;
Q->y = S.Top->y;
}
void Create(SeqStack &S,int N)
{
bool flag;
Queen* p=new Queen;
int total = 0;
p->x = 1;
p->y = 1;
Push(S, p);
p->x = 2;
p->y = 1;
while (p->x <= N && p->y <= N)
{
while (p->y <= N)
{
flag = Check(S, p);
if (flag) break;
p->y++;
}
if (flag)
{
Push(S, p);
p->x++;
p->y = 1;
if (p->x > N)
{
StackTraverse(S);
total++;
Pop(S, p);
p->y++;
while (p->y > N && S.Base != S.Top)
{
Pop(S, p);
p->y++;
}
}
}
else
{
Pop(S, p);
p->y++;
while (p->y > N && S.Base != S.Top)
{
Pop(S, p);
p->y++;
}
}
}
cout <<"解个数:" << total;
}
int main()
{
int N;
cin >> N;
SeqStack S;
InitStack(S, N);
cout << "皇后坐标:"<<endl;
Create(S, N);
return 0;
}
N皇后问题(C++栈)
最新推荐文章于 2024-05-02 11:18:45 发布