Skip to content

Instantly share code, notes, and snippets.

@WeiGrand
Created August 14, 2019 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WeiGrand/7716efdd2782751de49e33e012a69316 to your computer and use it in GitHub Desktop.
Save WeiGrand/7716efdd2782751de49e33e012a69316 to your computer and use it in GitHub Desktop.
/**
* Get all solutions of `n queens` problem
* https://zh.wikipedia.org/wiki/%E5%85%AB%E7%9A%87%E5%90%8E%E9%97%AE%E9%A2%98
* @param n
* @returns {*}
* @constructor
*/
const Nqueens = n => {
if (typeof n !== 'number') {
console.warn('Expect `n` to be a number got ' + typeof n + '.');
return;
}
if (n < 4) {
console.warn('No solution.');
return;
}
const row = n;
const col = n;
const result = [];
const results = [];
let i = 0;
let start = 0;
while (i >= 0 && i < row) {
let success = false;
for (let j = start; j < col; j++) {
if (success || result.some(r => {
const [
ri,
rj
] = r;
return ri === i || rj === j || Math.abs(ri - i) === Math.abs(rj - j);
})) {
continue;
}
result.push([i, j]);
success = true;
}
if (success) {
i++;
start = 0;
}
if (result.length === col) {
results.push(result.concat());
}
if (result.length === col || !success) {
const last = result.pop();
if (last) {
start = last[1] + 1;
i--;
} else {
i--;
start = 0;
}
}
}
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment