Typorithm · hard

N-Queens

▷ Interactive algorithm labn-queensbacktrackingconstraintsdiagonalschoose-explore-undo
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn N-Queens

0%

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.

Preparing algorithm lab…
01

One queen per row.

02

Track col, row-col, and row+col.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Board filled

Placing a queen on every row yields one valid arrangement.

if (row === n)

2. Attack check

Reject a square attacked on its column or either diagonal.

if (cols.has(col) || diag.has(row - col) || anti.has(row + col))

3. Place queen

Mark the column and both diagonals as occupied.

cols.add(col)

4. Next row

Move to the next row to place the following queen.

backtrack(row + 1)

5. Remove (undo)

Free the column and diagonals before trying another square.

cols.delete(col)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

N-Queens: Visual Walkthrough & Practice · Typorithm | ApplyDjinn