N皇后 II
Pcjmy opened this issue · comments
N皇后 II
题目链接: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;
};
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;
};