八皇后问题,解决思路和代码

相关问题1:[LeetCode] N-Queen N皇后

相关问题2:

八皇后问题,是一个古老而著名的问题,是回溯算法的典型例题。

这里给出八皇后问题的解答。思路是:对解答树进行深度遍历,当遍历抵达第8层的时候,我们便找到了一个解。如果在抵达第8层之前,发现解答树的节点违反了八皇后问题的要求,那么进行回溯。

具体的代码如下:

#include<iostream>
#include<vector>
#include<iterator>
using namespace std;

bool test_col(int c, vector<bool> col)
{// true if the c-th column is occupied.
        return col.at(c);
}

bool test_main(int r, int c, vector<bool> main_diag)
{// true if the main diag passing through (r,c) is occupied 
        return main_diag.at(r-c+7);
}

bool test_counter(int r, int c, vector<bool> counter_diag)
{// true if the counter diag passing through (r, c) is occupied
        return counter_diag.at(r+c);
}

void eight_queen(vector<int> pos, vector<bool> col, vector<bool> main_diag, vector<bool> counter_diag)
{
        if(pos.size()==8)
        {
                // copy can be used to print out the elements in an iterator range
                copy(pos.begin(), pos.end(), ostream_iterator<int>(cout, "|") );
                cout<<"\n";
                return;
        }
        else
        {
                for(int i=0; i<8; i++)
                {
                        if(!(test_col(i, col) || test_main(pos.size(), i, main_diag) || test_counter(pos.size(), i, counter_diag) ))
                        {
                                col.at(i) = true;
                                main_diag.at(pos.size()-i+7) = true;
                                counter_diag.at(pos.size()+i) = true;
                                pos.push_back(i);
                                eight_queen(pos, col, main_diag, counter_diag);
                                pos.pop_back();
                                col.at(i) = 0;
                                main_diag.at(pos.size()-i+7) = 0;
                                counter_diag.at(pos.size()+i) = 0;
                        }
                }
        }
        return;
}

int main()
{
        vector<bool> col(8, 0); // false: no queen is occupying this column. true: a queen is now occupying this column.
        vector<bool> main_diag(15, 0); // false: no queen is occupying this main diag. true: a queen is now occupying this main diag.
        vector<bool> counter_diag(15, 0); // false: no queen is occupying this counter diag. true: a queen is now occupying this counter diag.
        vector<int> pos;
        eight_queen(pos, col, main_diag, counter_diag);
}


你可能感兴趣的:(八皇后问题,解决思路和代码)