[leetcode]N-Queens

八皇后,学递归入门题

判重复的技巧,就是对角线

x+y , x-y这样判断两个对角线了,把二维坐标压缩到一维,方便点。。

class Solution {
public:
    bool col[100];
    bool d1[100]; // i + j
    bool d2[100]; // i - j + n
    int cnt[100];
    
    void nque(vector<vector<string> >& ans , int n , int dep) {
        if(dep >= n) {
            vector<string> xx(n);
            for(int i = 0 ; i < n ; i++) {
                string tmp = string(n , '.');
                tmp[cnt[i]] = 'Q';
                xx[i] = tmp;
            }
            ans.push_back(xx);
            return ;
        }
        
        for(int i = 0 ; i < n ; i++) {
            if(col[i] && d1[dep+i] && d2[dep-i+n]) {
                cnt[dep] = i;
                col[i] = false;
                d1[dep+i] = false;
                d2[dep-i+n] = false;
                nque(ans , n , dep + 1);
                col[i] = true;
                d1[dep+i] = true;
                d2[dep-i+n] = true;
            }
        }
    }
    vector<vector<string> > solveNQueens(int n) {
        memset(col , true , sizeof(col));
        memset(d1 , true , sizeof(d1));
        memset(d2 , true , sizeof(d2));
        vector<vector<string> > ans;
        nque(ans , n , 0);
        return ans;
    }
};
原文地址:https://www.cnblogs.com/x1957/p/3515411.html