5
var totalNQueens = function (n) {6
// Keep track of columns with queens7
const cols = new Set();8
// Keep track of positive slope diagonal by storing row number + column number9
const posDiag = new Set();10
// Keep track of negative slope diagonal by storing row number - column number11
const negDiag = new Set();12
// Count of valid boards15
const backtrack = function (r) {16
// Base case to end recursion, we have traversed board and found valid position in each row21
// Loop through each column to see if you can place a queen22
for (let c = 0; c < n; c++) {23
// invalid position check, if position in set we cannot place queen here24
if (cols.has(c) || posDiag.has(r + c) || negDiag.has(r - c)) continue;26
// add new queen to sets34
// remove current position from sets because backtracking for this position is complete36
posDiag.delete(r + c);37
negDiag.delete(r - c);