您的位置:首页 > 产品设计 > UI/UE

AI-N Queen Problem(bfs)

2015-09-16 16:37 465 查看
#include <cstdio>//because of the limit of the queue's length,the biggest N is only 14(2s).And I really don't think bfs is a good way to solve this queen problem.
#include <iostream>
#include <algorithm>

#define BG 10000000
using namespace std;

struct point{
int row;
int col;
struct point* upper;//to find the "parent" queen of this point
};

point* q[BG];//because I must find the whole way according to "upper",so I can't use "queue" and "pop()" to delete the head point.
int h,t;
int n;
bool check(point* w,int nc)//to check whether the nc place is proper below w queen.
{
point* p;
p=w;
int nr;
nr=w->row+1;
while(p!=NULL)
{
if((p->col==nc)||(nr-p->row)==abs(nc-p->col))
return false;
p=p->upper;
}
return true;
}

void print_out(point* last)//print out the result
{
point *b=last;
while(b!=NULL)
{
printf("(%d,%d) ",b->row,b->col);
b=b->upper;
}
cout<<endl;
}

int main()
{
cin>>n;
int i;
for(i=1;i<=n;i++)
{
q[i]=(point*)malloc(sizeof(point));
q[i]->row=1;
q[i]->col=i;
q[i]->upper=NULL;
}
h=1;
t=n;
while(h!=t)
{
point* w;
w=q[h++];//fetch the head point of the queen
int nc;
for(nc=1;nc<=n;nc++)
{
if(check(w,nc))//the lower queen below w-queen in the nc col
{
q[t]=(point*)malloc(sizeof(point));
q[t]->row=w->row+1;
q[t]->col=nc;
q[t]->upper=w;
if(q[t]->row==n)
{
print_out(q[t]);
return 0;
}
t++;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: