八皇后,学递归入门题

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

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;
    }
};

 

相关文章:

  • 2022-02-27
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
  • 2021-10-17
  • 2021-08-27
  • 2022-02-12
猜你喜欢
  • 2021-07-20
  • 2021-09-16
  • 2021-10-07
  • 2021-11-17
  • 2021-08-27
  • 2021-09-16
相关资源
相似解决方案