Skip to content

Instantly share code, notes, and snippets.

@lqt0223
Created March 13, 2018 05:31
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 lqt0223/93775143a9f9a6d4e056f5f5674e398f to your computer and use it in GitHub Desktop.
Save lqt0223/93775143a9f9a6d4e056f5f5674e398f to your computer and use it in GitHub Desktop.
29 n-queens puzzle - the backtracking solution
// the backtracking (one kind of recursion) code paradigm:
// - build a helper function with extra arguments to pass on choices and other useful information during recursive calls
// - in the helper function, the base case is for handling the result after series of choices
// - in the helper function, the recursive case is usually in the 'choose-explore-unchoose' pattern
function queen(size) {
var result = queenHelper(size, [], [])
return result
}
function queenHelper(size, chosen, solutions) {
if (chosen.length == size) {
solutions.push(chosen.slice())
} else {
for (var i = 0; i < size; i++) {
if (safe(i, chosen)) {
chosen.push(i)
queenHelper(size, chosen, solutions)
chosen.pop()
}
}
return solutions
}
}
function safe(x, positions) {
return !included(x, positions) && !diagonal(x, positions)
}
function included(x, arr) {
return arr.some(i => i == x)
}
function diagonal(x, arr) {
return arr.some((t, i) => x - arr.length == t - i || x + arr.length == t + i)
}
var result = queen(8)
console.log(result.length) // 92
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment