#include #include #include #include #include using namespace std; /* This solves the N-queen problem in C++ using recursion */ /* Sample Makefile BOOST_ROOT=/var/tmp/omiga/boost_1_40_0 solve_n_queen: solve_n_queen.cc g++ -I$(BOOST_ROOT) -g -o $@ $< */ // return solutions which are vector of vector of ints typedef vector single_solution; typedef vector free_cols; typedef vector solutions; free_cols get_free_cols(const single_solution& s, const int n) { set used_cols; free_cols f; BOOST_FOREACH(int col, s) { used_cols.insert(col); } for (int i=1; i<=n; i++) { if (used_cols.find(i) == used_cols.end()) { f.push_back(i); } } return f; } bool is_there_any_piece_at_row_col(const int row, const int col, const single_solution& s) { int count = 1; BOOST_FOREACH(int p, s) { if ((row == count) && (col == p)) { return true; } ++count; } return false; } bool can_attack(const int col, const single_solution& s, const int n) { int row; row = s.size() + 1; for (int i=1; (i<=col-1) && ((row-i)>0); ++i) { if (is_there_any_piece_at_row_col(row-i, col-i, s)) { return true; } } for (int i=col+1; (i<=n) && (row-(i-col)>0); ++i) { if (is_there_any_piece_at_row_col(row-(i-col), i, s)) { return true; } } return false; } void print_solutions(const solutions& ss) { int count =1; BOOST_FOREACH(single_solution s, ss) { cout<<"Solution "<