分枝界限法-N皇后问题代码
#include <iostream>
#include <cmath>
#include <queue>
using namespace std;
#define N 4
struct TreeNode
{
int * data;
int level;
};
bool validate(TreeNode &node,int nextLinePos)
{
int *p = node.data;
int nextLineNum = node.level+1;
for(int i=0;i<=node.level;i++)
{
if(nextLinePos==p[i]||abs(nextLineNum-i)==abs(nextLinePos-p[i]))
{
return false;
}
}
return true;
}
int main()
{
queue<TreeNode> qu;
for(int i=0;i<4;i++)
{
TreeNode treeNode;
treeNode.level = 0;
treeNode.data = new int[N];
treeNode.data[0]=i;
qu.push(treeNode);
}
while(true)
{
if(qu.empty())
{
cout<<"no answer"<<endl;
return 1;
}
else
{
TreeNode node = qu.front();
qu.pop();
for(int i=0;i<N;i++)
{
if(validate(node,i))
{
if(node.level==N-2)
{
node.data[node.level+1]=i;
cout<<"true"<<endl;
for(int i=0;i<N;i++)
{
cout<<node.data[i]<<endl;
}
}
else
{
node.level = node.level+1;
node.data[node.level]=i;
qu.push(node);
}
}
}
}
}
return 0;
}
#include <cmath>
#include <queue>
using namespace std;
#define N 4
struct TreeNode
{
int * data;
int level;
};
bool validate(TreeNode &node,int nextLinePos)
{
int *p = node.data;
int nextLineNum = node.level+1;
for(int i=0;i<=node.level;i++)
{
if(nextLinePos==p[i]||abs(nextLineNum-i)==abs(nextLinePos-p[i]))
{
return false;
}
}
return true;
}
int main()
{
queue<TreeNode> qu;
for(int i=0;i<4;i++)
{
TreeNode treeNode;
treeNode.level = 0;
treeNode.data = new int[N];
treeNode.data[0]=i;
qu.push(treeNode);
}
while(true)
{
if(qu.empty())
{
cout<<"no answer"<<endl;
return 1;
}
else
{
TreeNode node = qu.front();
qu.pop();
for(int i=0;i<N;i++)
{
if(validate(node,i))
{
if(node.level==N-2)
{
node.data[node.level+1]=i;
cout<<"true"<<endl;
for(int i=0;i<N;i++)
{
cout<<node.data[i]<<endl;
}
}
else
{
node.level = node.level+1;
node.data[node.level]=i;
qu.push(node);
}
}
}
}
}
return 0;
}