您的位置:首页 > 产品设计 > UI/UE

N-Queens II DFS

2015-07-06 11:03 549 查看
思路:

DFS。与上一题相同,直接求出解的个数即可。不必记录所有的解。

时间复杂度O(N!),空间复杂度O(N)。

class Solution {
private:
    int ans = 0; 
    bool canSet(vector<int> &map, int n, int row, int col) {
        for(int tmprow = 0; tmprow < row; ++tmprow) {
            int tmpcol = map[tmprow];
            if(tmpcol == col) // row
                return false;
            if((tmpcol - col) == (tmprow - row)) // right slant line
                return false;
            if((tmpcol - col) == (row - tmprow)) // left slant line
                return false;
        }
        return true;
    }
    void dfs(vector<int> &map, int n, int row) {
        for(int i = 0; i < n; ++i) {
            if(canSet(map, n, row, i)) {
                map[row] = i;
                if(row == n - 1) {
                    ++ans;
                    map[row] = 0;
                    return;
                }
                dfs(map, n, row+1);
                map[row] = 0;
            }
        }
    }
public:
    int totalNQueens(int n) {
        vector<int> map = vector<int>(n, 0);
        dfs(map, n, 0);
        return ans;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: