-
-
Notifications
You must be signed in to change notification settings - Fork 235
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
Comments
@Pcjmy 哥们 你发这么多issue 能顺便把你的答案附上吗? |
可以 |
题目链接:https://leetcode.cn/problems/n-queens-ii/description /**
* @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;
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: