-
-
Notifications
You must be signed in to change notification settings - Fork 243
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皇后 #441
Comments
题目链接:https://leetcode.cn/problems/n-queens /**
* @param {number} n
* @return {string[][]}
*/
var solveNQueens = function(n) {
let ans=[];
let arr=new Array(n); // 存放解决方案
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) {
let A=[];
for(let i=0;i<n;i++) {
let str='';
for(let j=0;j<n;j++) {
if(arr[i]===j) {
str+='Q';
} else {
str+='.';
}
}
A.push(str);
}
ans.push(A);
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;
arr[x]=i;
dfs(x+1);
col[i]=vis1[u]=vis2[v]=0;
}
}
}
dfs(0);
return ans;
}; |
|
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: