1. Board filled
Placing a queen on every row yields one valid arrangement.
if (row === n)Typorithm · hard
Step 1 of 8 · intro card
Backtracking
Place one queen per row, rejecting squares attacked on a column or diagonal, with sets as O(1) guards.
One queen goes in each row, so the search only chooses a column per row.
A square is safe unless its column, its row-minus-col diagonal, or its row-plus-col anti-diagonal is taken.
Three sets make each safety check O(1); add on place and delete on undo.
One queen per row.
Track col, row-col, and row+col.
Add to place, delete to undo.
function totalNQueens(n) {
let count = 0;
const cols = new Set();
const diag = new Set();
const anti = new Set();
function backtrack(row) {
if (row === n) {
count += 1;
return;
}
for (let col = 0; col < n; col += 1) {
if (cols.has(col) || diag.has(row - col) || anti.has(row + col)) {
continue;
}
cols.add(col);
diag.add(row - col);
anti.add(row + col);
backtrack(row + 1);
cols.delete(col);
diag.delete(row - col);
anti.delete(row + col);
}
}
backtrack(0);
return count;
}Connect each part of the code to the concept before you type.
Placing a queen on every row yields one valid arrangement.
if (row === n)Reject a square attacked on its column or either diagonal.
if (cols.has(col) || diag.has(row - col) || anti.has(row + col))Mark the column and both diagonals as occupied.
cols.add(col)Move to the next row to place the following queen.
backtrack(row + 1)Free the column and diagonals before trying another square.
cols.delete(col)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
Input4 × 4 board · one queen per row
Follow temporary values, local state and supporting structures at this step.
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state