关闭

#34 N-Queens II

标签: lintcodeDFS
64人阅读 评论(0) 收藏 举报
分类:

题目描述:

Follow up for N-Queens problem.

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

Example

For n=4, there are 2 distinct solutions.

题目思路:

这题和#33 差不多,把最后的ans改成count就好了。

Mycode(AC = 171ms):

class Solution {
public:
    /**
     * Calculate the total number of distinct N-Queen solutions.
     * @param n: The number of queens.
     * @return: The total number of distinct solutions.
     */
    int totalNQueens(int n) {
        // write your code here
        int count = 0;
        if (n == 0) return count;
        
        vector<string> sofar;
        unordered_set<int> col, diag;
        solveNQueens(count, sofar, n, col, diag);
        return count;
    }
    
    void solveNQueens(int& count,
                      vector<string>& sofar,
                      int n,
                      unordered_set<int>& col,
                      unordered_set<int>& diag)
    {
        if (sofar.size() == n) {
            count++;
            return;
        }
        
        string tmp = nDots(n);
        for (int i = 0; i < n; i++) {
            // if there is no Q in same row, col, and diag,
            // then tmp could be a potential ans
            if (col.find(i) == col.end() &&
                !findDiag(diag, sofar.size(), i, n))
            {
                col.insert(i);
                diag.insert(sofar.size() * n + i);
                tmp[i] = 'Q';
                sofar.push_back(tmp);
                
                solveNQueens(count, sofar, n, col, diag);
                
                sofar.pop_back();
                tmp[i] = '.';
                diag.erase(sofar.size() * n + i);
                col.erase(i);
            }
        }
    }
    
    // write n '.' in a line
    string nDots(int n) {
        string str = "";
        for (int i = 0; i < n; i++) {
            str += ".";
        }
        return str;
    }
    
    // check whether there is Q in diag
    bool findDiag(unordered_set<int>& diag, int i, int j, int n) {
        for (auto it = diag.begin(); it != diag.end(); it++) {
            int row = *it / n;
            int col = *it % n;
            
            if (abs(row - i) == abs(col - j)) return true;
        }
        
        return false;
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12141次
    • 积分:2243
    • 等级:
    • 排名:第16794名
    • 原创:221篇
    • 转载:1篇
    • 译文:0篇
    • 评论:10条
    文章分类
    文章存档