Leetcode-52.N-Queens

来源:互联网 发布:心酸的句子知乎 编辑:程序博客网 时间:2024/05/04 08:33

Problem:
1. return the all configuration the vector of the chessborad
2. return the amount of of distinct solution


Analysis:
The idea is using DFS search with backtracking in recursive.
We use a 1D vector(n, 0) to store the position of Queen in each row.
Starting the first row, try each column. If it’s valid,we move to the next row and try each column. If the position will induce attack. we try next column. If can’t find a valid position in the current row, we backtrack to the previous row and try next next column.

Solution of problem 1:

class Solution { public:     vector< vector <string> > solveNQueens(int n)  {      vector<vector<string> > res;    vector<int> v(n, 0);    helper(n, 0, res, v);    return res; } void helper(int n, int start, vector<vector<string> >& res, vector<int>& v) {    if (start == n)    {        res.push_back(toStr(v));        return;    }    for (int index = 0; index < n; ++index)    {        v[start] = index;        if (isValid(v, start))        helper(n, start + 1, res, v);    } } bool isValid(vector<int> & v, int n) {      for (int i = 0; i < n; i++)    {        if(abs(n - i) == abs(v[n] - v[i]) || v[i] == v[n])            return 0;    }    return 1; } vector<string> toStr(vector<int>& v){    int n = v.size();    vector<string> rel;    for (int i = 0; i < n; ++i)    {        string t(n, '.');        t[v[i]] = 'Q';        rel.push_back(t);    }    return rel; }};

Solution of problem 2 :

class Solution {public:   int totalNQueens(int n) {    int count = 0;    vector<int> v(n, 0);    helper(n, 0, count, v);    return count;}void helper(int n, int start, int& count, vector<int>& v){    if (start == n)    {        count++;        return;    }    for (int i = 0; i < n; ++i)    {        v[start] =  i;        if (isValid(v, start))            helper(n, start + 1, count, v);    }}    bool isValid(vector<int>& v, int start)    {        for (int i = 0; i < start; ++i)            if (abs(i - start) == abs(v[i] - v[start]) || v[i] == v[start]) return 0;        return 1;    }};
0 0
原创粉丝点击