N皇后问题(C++栈)

#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;
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值