八皇后问题(非递归版)

本文介绍了一种使用栈和回溯法解决八皇后问题的算法实现。通过定义栈结点来表示皇后的放置位置,并利用互斥标志进行冲突检测,最终输出所有可行解及其数量。
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->#include<iostream>
#include
<stack>
usingnamespacestd;

constintMAXSIZE=8;//棋盘大小
intchess[MAXSIZE][MAXSIZE]={0};//棋盘
/*
定义栈结点,表示一个皇后的位置*/
structNode
{
introw;/**/
intcol;/**/
boolisMarked;/*是否标记*/
};

/*进行皇后问题处理
*返回找到的答案个数
*/
intSolve()
{
//定义解答树堆栈
stack<Node>stack;
//互斥标志,表示同一列及对角线上是否有皇后
intcol[MAXSIZE]={0},
md[
2*MAXSIZE-1]={0},
sd[
2*MAXSIZE-1]={0};
intstr,stc,i,j;
//解决方案个数
intscount=0;
NodetopNode;
//初始化栈
for(i=0;i<MAXSIZE;i++)
{
topNode.row
=0;
topNode.col
=MAXSIZE-1-i;
topNode.isMarked
=false;
stack.push(topNode);
}
//以行为单位开始回溯
while(!stack.empty())
{
topNode
=stack.top();//栈顶元素
str=topNode.row;//
stc=topNode.col;//
if(topNode.isMarked==false)
{
//如果栈顶元素的位置并没有确立
if(col[stc]||md[str-stc+MAXSIZE-1]||sd[str+stc])
{
//如果同一列或同一对角线上已有皇后,则退回*/
stack.pop();
}
else
{
//占据这个位置,设置列、对角线上的互斥标志
col[stc]=1;
md[str
-stc+MAXSIZE-1]=1;
sd[str
+stc]=1;
//标记栈顶元素的isMarked值
topNode.isMarked=true;
stack.pop();
stack.push(topNode);
chess[str][stc]
=1;//标记棋盘对应位置
if(str==MAXSIZE-1)
{
//如果此时已经到达最后一行,则表示此种布局方法是成功的,输出相关信息
cout<<"Asolutionis:"<<endl;
for(i=0;i<MAXSIZE;++i)
{
for(j=0;j<MAXSIZE;++j)
{
if(chess[i][j]==1)
{
cout
<<"("<<i+1<<","<<j+1<<")";
}
}
}
cout
<<endl;
scount
++;//解决方案数增
}
else
{
//如果此时没有到达最后一行,则继续进栈并初始化
for(i=0;i<MAXSIZE;i++)
{
topNode.row
=str+1;
topNode.col
=MAXSIZE-1-i;
topNode.isMarked
=false;
stack.push(topNode);
}
}
}
}
else
{
//如果栈顶元素位置已确立,则栈顶元素出栈,初始化互斥标志,准备继续寻找其它的方法
col[stc]=0;
md[str
-stc+MAXSIZE-1]=0;
sd[str
+stc]=0;
chess[str][stc]
=0;
stack.pop();
}
}
returnscount;
}
intmain()
{
intscount=0;
scount
=Solve();
cout
<<scount<<"sulotionsfound."<<endl;
system(
"pause");
return0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值