[leetcode刷题系列]N-Queens 2

囧,  和上题基本上一样,没啥好说的

class Solution {
    const static int MAXN = 100;
    bool col[MAXN], add[MAXN], minus[MAXN];
    int ans[MAXN];
    void dfs(int now, int n, int& ret){
        if(now >= n){
            ++ ret;
            return ;
        }
        for(int i = 0; i < n; ++ i){
            if(!col[i] && !add[now + i] && !minus[now - i + n]){
                col[i] = true;
                add[now + i] = true;
                minus[now - i + n] = true;
                ans[now] = i;
                dfs(now + 1, n, ret);
                col[i] = false;
                add[now + i] = false;
                minus[now - i + n] = false;
            }
        }
    }
public:
    int totalNQueens(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        memset(col, 0x00, sizeof(col));
        memset(add, 0x00, sizeof(add));
        memset(minus, 0x00, sizeof(minus));
        int ret = 0;
        dfs(0, n, ret);
        return ret;
    }
};


你可能感兴趣的:([leetcode刷题系列]N-Queens 2)