leetcode-----52. N皇后 II

代码

class Solution {
public:
    vector<bool> col, dg, udg;
    int ans, N;

    int totalNQueens(int n) {
        N = n;
        col = vector<bool>(N);
        dg = udg = vector<bool>(N * 2);

        dfs(0);
        return ans;
    }

    void dfs(int u) {
        if (u == N) {
            ans++;
            return;
        }
        for (int i = 0; i < N; ++i) {
            if (!col[i] && !dg[u - i + N] && !udg[u + i]) {
                col[i] = dg[u - i + N] = udg[u + i] = true;
                dfs(u + 1);
                col[i] = dg[u - i + N] = udg[u + i] = false;
            }
        }
    }
};
posted @ 2020-07-07 09:22  景云ⁿ  阅读(48)  评论(0编辑  收藏  举报