分享
 
 
 

The BackTracking algorithm for n queen problem

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

The article is about the design of algorithm for n queen problem. The intention of this article is from an excise of an algorithm book: <<Introduction to the design and analysis of algorithms>>. This backtracking algorithm is interesting, so I decide to record the process of implementation. First, I use a double dimension array to simulate the chess board. But quickly I have found this form of representation is not so convenient especially in the check function that is used to checking whether or not current solution is promising. Because the check function is worked with the index of array, the value of array is trivial. i.e. a[0][0] = 1 represent (0,0) position of chess board has a chess and the next chess can't be position (0,1) and (0,0). So I have changed a representation of chess position by vector<pair<int,int> >. Apparently, pair<int, int> stands for (x,y). Notice that a solution of n queen require each row is different. That is, for a solution of n queen, each of pair_instance.first must distinct. This simplifies the representation further. It just needs a vector<int> to represent a chess board. So the solution of n queen problem can be viewed as a permutation of natural number from 0 to n-1. Apparently, the brute-force algorithm has efficiency Ω(n!).

For the part of check function, I have observed the characteristic of permutation that is confirmed with n queen problem. The rule is defined as follow:

If the number of position p in permutation is i, then position q can't be q-p+i or p-q+i.(q∈(p,n-1] );

It requires a two nested for loop to attaining. In addition, if there exist a method to constructing a NFA to recognize the permutation, the n queen problem algorithm will have Θ(n) efficiency class. But it seems impossible to do that because the FA needs counting and no way to abstract states.

The codes:

#include <iostream>

#include <vector>

#include <algorithm>

#include <utility>

#include <functional>

#include <ctime>

using namespace std;

template<class T>

struct output_functor : public unary_function<T,void>

{

void operator()(const T& p)const

{

cout<<"("<<p.first<<","<<p.second<<")"<<" ";

}

};

class chess_board

{

vector<pair<int, int> > position;

vector<int> array;

vector<int> duplicate_array;

public:

int n;

int cur_i;

int number_solution;

chess_board(int dim):n(dim),cur_i(0),number_solution(0)

{

position.reserve(n);

array.resize(n,-30000);//if using -1 to denoting no chess, it will contradict with the diagonal test. i.e. move{0,0}.the content of array is {0,-1,-1,-1}.the diagonal test will return false. So I use -30000 to express the meaning, but it is still imperfect. it is requiring a number to denoting impossible number or infinity simply

duplicate_array.resize(n,0);

for(int i=0; i<n; i++)

{

position.push_back(make_pair(i,-1));

}

}

void move(int j)

{

position[cur_i].second=j;

array[cur_i]=j;

if(duplicate_array[j]==0)

duplicate_array[j]=1;

else

duplicate_array[j]=2;

}

void un_move(int j)

{

position[cur_i].second=-1;

array[cur_i]=-30000;

if(duplicate_array[j]==1)

duplicate_array[j]=0;

else

duplicate_array[j]=1;

}

bool check()

{

vector<int>::iterator i = std::find(duplicate_array.begin(),duplicate_array.end(),2);

if(i != duplicate_array.end())

return false;

if(check_permutation(array) == false)

return false;

return true;

}

void write()

{

number_solution++;

for_each(position.begin(), position.end(), output_functor<pair<int,int> >());

cout<<endl;

}

private:

bool check_permutation(const vector<int>& p)

{

for(int i=0; i<n; i++)

{

for(int j=i+1,d=1; j<n; j++,d++)

{

if(p[i]+d == p[j] || p[i]-d == p[j])

return false;

}

}

return true;

}

};

void BackTracking(chess_board& c)

{

if(c.check() == false)

{c.cur_i -= 1;return;}

else

{

if(c.cur_i == c.n)// this judgment is some tricky, note that following a move(), and assuming a solution has been generated, then cur_i will increase by 1.so in the recurrence of BackTracking cur_i will exceed the meaning of a position so that it will compare with n rather than n-1

{

c.write();

c.cur_i-=1; //this sentence is cope with the situation in which BackTracking terminated after a solution has been found

return;

}

else

{

for(int j=0; j<c.n; j++)

{

c.move(j);

c.cur_i += 1;

BackTracking(c);

c.un_move(j);

}

c.cur_i -= 1; //this sentence is cope with the situation in which BackTracking terminated after for loop over

}

}

}

int main()

{

clock_t t1 = clock();

int n;

cout<<"input the number of queen: ";

cin>>n;

chess_board c(n);

BackTracking(c);

cout<<"The number of solutions is: "<<c.number_solution<<endl;

clock_t t2 = clock();

cout<<"Times took:"<<double(t2-t1)/CLOCKS_PER_SEC;

system("pause");

return 0;

}

Note that this is just a “pure” BackTracking algorithm and it has not considered the optimization. I will optimize it later.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有