Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

N皇后 II

Pcjmy opened this issue · comments

commented
N皇后 II
commented

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

commented

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

可以

commented

题目链接: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;
};
commented
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;
};