欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

leetcode---N-Queens II

最编程 2024-03-14 20:02:42
...

Follow up for N-Queens problem.

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

这里写图片描述

class Solution {
public:
    int ans = 0;

    bool ok(int depth, int col, int n, vector<string> &tmp)
    {
        int sum = col + depth;
        int c = 0;
        for(int i=0; i<depth; i++) 
        {
            c = depth - i;
            if(tmp[i][col] == 'Q' || tmp[i][sum-i] == 'Q' || tmp[i][col-c] == 'Q')
                return false;
        }
        return true;
    }

    void dfs(int depth, vector<string> &tmp, int n)
    {
        if(depth >= n)
        {
            ans++;
            return;
        }
        for(int j=0; j<n; j++)
        {
            tmp[depth][j] = 'Q';
            if(ok(depth, j, n, tmp))
                dfs(depth+1, tmp, n);
            tmp[depth][j] = '.';
        }
    }

    int totalNQueens(int n) 
    {
        vector<string> tmp;
        for(int i=0; i<n; i++)
        {
            string s = "";
            for(int j=0; j<n; j++)
                s += '.';
            tmp.push_back(s);
        }
        dfs(0, tmp, n);
        return ans;

    }
};