← All Exercises
Count N-Queens Solutions with Backtracking
advancedtypescript
Background
N-Queens is the standard exercise for constrained backtracking and symmetry pruning in combinatorial search.
Problem
Given an integer n, return the number of distinct ways to place n queens so that no two share a row, column, or diagonal.
Input
An integer n between 1 and 10 inclusive.
Output
The count of valid board configurations as a number.
Sample tests
Sample 1
Input: n = 4
Expected: 2
Sample 2
Input: n = 1
Expected: 1
Sample 3
Input: n = 8
Expected: 92
Your solution
Learning objective
Encode diagonal conflicts with row - column and row + column invariants and undo state during backtracking.