Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

N皇后 II #442

Open
Pcjmy opened this issue Jan 29, 2023 · 4 comments
Open

N皇后 II #442

Pcjmy opened this issue Jan 29, 2023 · 4 comments

Comments

@Pcjmy
Copy link
Contributor

Pcjmy commented Jan 29, 2023

No description provided.

@zyyv
Copy link

zyyv commented Jan 30, 2023

@Pcjmy 哥们 你发这么多issue 能顺便把你的答案附上吗?

@Pcjmy
Copy link
Contributor Author

Pcjmy commented Jan 30, 2023

@Pcjmy 哥们 你发这么多issue 能顺便把你的答案附上吗?

可以

@Pcjmy
Copy link
Contributor Author

Pcjmy commented Jan 30, 2023

题目链接:https://leetcode.cn/problems/n-queens-ii/description
时间复杂度:O(N!)

/**
 * @param {number} n
 * @return {number}
 */
var totalNQueens = function(n) {
    let ans=0;
    let col=new Array(n); // 标记当前列有没有皇后
    let vis1=new Array(2*n); // 标记y=-x方向有没有皇后
    let vis2=new Array(2*n); // 标记y=x方向有没有皇后
    function dfs(x) {
        if(x===n) {
            ans++;
            return ;
        }
        for(let i=0;i<n;i++) {
            let u=x+i;
            let v=x-i+n;
            if(!col[i]&&!vis1[u]&&!vis2[v])
            {
                col[i]=vis1[u]=vis2[v]=1;
                dfs(x+1);
                col[i]=vis1[u]=vis2[v]=0;
            }
        }
    }
    dfs(0);

    return ans;
};

@bearki99
Copy link

bearki99 commented Feb 1, 2023

var totalNQueens = function(n) {
    const col = new Array(n).fill(false), deg = new Array(2*n).fill(false), redeg = new Array(2*n).fill(false);
    const char = Array.from(new Array(n), ()=>new Array(n).fill('.'));
    let res = 0;
    function dfs(u){
        if(u===n){
            res++;
            return;
        }
        for(let i = 0 ; i < n ; i++){
            if(!col[i] && !deg[u+i] && !redeg[i-u+n]){
                char[u][i] = 'Q';
                col[i] = deg[u+i] = redeg[i-u+n] = true;
                dfs(u+1);
                col[i] = deg[u+i] = redeg[i-u+n] = false;
                char[u][i] = '.';
            }
        }
    }
    dfs(0);
    return res;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants