[leetcode] 52. N-Queens II 解题报告

题目链接:https://leetcode.com/problems/n-queens-ii/

Follow up for N-Queens problem.

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


思路:和N-Queens problem一样,这个不需要打印出棋盘,因此还要更简单一些。点击这里看上题的解题报告。

代码如下:

class Solution {
public:
    void DFS(vector& map, int k, int n, int& ans)
    {
        if(k == n) { ans++; return; }
        for(int i = 0, x, y; i < n; i++)
        {
            for(y = 0; y < k; y++)
                if(map[y][i] == 'Q') break;
            if(y != k) continue;
            for(y = k, x = i; y >=0&&x=0 && x >=0; y--, x--)
                if(map[y][x] == 'Q') break;
            if(!(y<0 || x < 0)) continue;
            map[k][i] = 'Q';
            DFS(map, k+1, n, ans);
            map[k][i] = '.';
        }
    }
    
    int totalNQueens(int n) {
        vector map(n, string(n, '.'));
        int ans = 0;
        DFS(map, 0, n, ans);
        return ans;
    }
};

class Solution {
public:
    void DFS(vector>& hash, int n, int index, int& sum)
    {
        if(index >= n) { sum++; return; }
        for(int i = 0; i < n; i++)
        {
            if(!hash[0][i+index] && !hash[1][index-i+n] && !hash[2][i])
            {
                hash[0][i+index] = true;
                hash[1][index-i+n] = true;
                hash[2][i] = true;
                DFS(hash, n, index+1, sum);
                hash[0][i+index] = false;
                hash[1][index-i+n] = false;
                hash[2][i] = false;
            }
        }
    }
    int totalNQueens(int n) {
        if(n <= 0)  return 0;
        vector tem(2*n+1, false);
        vector> hash(3, tem);
        int sum = 0;
        DFS(hash, n, 0, sum);
        return sum;
    }
};


你可能感兴趣的:(leetcode,DFS,backtracking)