LeetCode 52. N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

image

上一题,稍微修改一下就可以了。

class Solution
{
    void dfs(vector<bool> &mk_col, vector<bool> &mk_l, vector<bool> &mk_r, int x, int &n, int &ans)
    {
        if(x == n)
        {
            ans ++;
            return ;
        }
        for(int i=0; i<n; ++ i)
        {
            if(mk_col[i] == false && mk_l[x-i+n] == false && mk_r[x+i] == false)
            {
                mk_col[i] = true, mk_l[x-i+n] = true, mk_r[x+i] = true;
                dfs(mk_col, mk_l, mk_r, x+1, n, ans);
                mk_col[i] = false, mk_l[x-i+n] = false, mk_r[x+i] = false;
            }
        }
    }
public:
    int totalNQueens(int n)
    {
        vector<bool> mk_col(n, false), mk_l(n<<1, false), mk_r(n<<1, false);

        int ans = 0;
        dfs(mk_col, mk_l, mk_r, 0, n, ans);
        return ans;
    }
};

posted @ 2017-04-04 21:25  aiterator  阅读(100)  评论(0编辑  收藏  举报