2011-05-24 22:57:12 n皇后问题6_6 测试数据 10 1 2 3 4 5 6 7 8 9 10 11 12 13 分支限界法 与广度优先的最大差别在于father.checkNext(i)剪枝函数会检测是否可进入下一个节点,如果不可进入,则后续的所有排列均不搜索 //Author:王子硕 Date:2011/5/24 //Description:经典n皇后问题 广度优先 建议n<=14 #include <iostream> #include <fstream> #include <algorithm> #include <functional> #include <queue> using namespace std; ifstream in("input.txt"); ofstream out("output.txt"); class Node{ public: Node(int n){ t = 0; this->n = n; loc = new int[n + 1]; for (int i = 0; i<= n; ++i) { loc[i] = 0; } } Node(const Node &other){ this->t = other.t; this->n = other.n; this->loc = new int [n + 1]; for (int i = 0; i <= n; ++i){ this->loc[i] = other.loc[i]; } } int t;//已放置t个皇后 int *loc;//loc[1:t] int n;//共放置n个皇后 bool checkNext(int next); void printQ(); }; bool Node::checkNext(int next){ int i,j; for (i = 1; i <= t; ++i) { if (loc[i] == next)//检测同行 { return false; } if (loc[i] - next == t + 1 - i)//检测反斜线 行差==列差 { return false; } if (loc[i] - next == i - t - 1)//检测正斜线 { return false; } } return true; } void Node::printQ(){ for (int i = 1; i <= n; ++i) { out<<loc[i]<<" "; } out<<endl; } class Queen{ public: int n;//n皇后 int ansNum;//对于n皇后解的个数 Queen(int n){ this->n = n; ansNum = 0; } void ArrangQueen(); }; void Queen::ArrangQueen(){ queue<Node> Q; Node ini(n); Q.push(ini); while(!Q.empty()){ Node father = Q.front(); Q.pop(); if (father.t == n) { father.printQ(); ++ansNum; } for (int i = 1; i <= n; ++i) { if (father.checkNext(i)) { Node Child(father); ++Child.t; Child.loc[Child.t] = i; Q.push(Child); } } } } int main(){ //#define in cin //#define out cout int cases; in>>cases; for(int Case = 1; Case <= cases; ++Case){ int n; in>>n; Queen Q(n); Q.ArrangQueen(); out<<"Case #"<<Case<<": "<<Q.ansNum<<endl; } return 0; }