[LeetCode] N-Queens II

Follow up for N-Queens problem.

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

 

思路:和 N-queens 一样,不过只统计个数而言,更加简单了

class Solution {
    vector<int> x;
    int m_res;

    bool checkTwoPoints(int i, int j, int xi, int xj)
    {
        //cout << "check i\t" << i << endl;
        //cout << "check j\t" << j << endl;
        if(xi == xj) // same column
            return false;
        if( abs(xi-xj) == abs(i-j)) // diag
            return false;
        return true;
    }

    bool check(vector<int> x, int n) // check x[n] and x[0 .. n-1]
    {
        for(int i = 0; i < n; i++)
        {
            if(!checkTwoPoints(i, n, x[i], x[n]))
                return false;
        }
        return true;
    }

    void dfs(int n)
    {
        if(n == x.size() )
        {   
            //printVector(x);
    
            m_res ++; 
            return;
        }   

        for(int i = 0; i < x.size(); i++)
        {
            x[n] = i;

            // check if x[n] is available
            if(check(x, n))
                dfs(n+1);
        }

    }
    public:
    int totalNQueens(int n)
    {
        x.resize(n);
        m_res = 0;

        dfs(0);
        return m_res;
    }
};

 

posted @ 2015-03-04 16:54  穆穆兔兔  阅读(146)  评论(0编辑  收藏  举报