Created
March 13, 2018 05:31
-
-
Save lqt0223/93775143a9f9a6d4e056f5f5674e398f to your computer and use it in GitHub Desktop.
29 n-queens puzzle - the backtracking solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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