codejump
HardPro challengePythonJavaScriptTypeScript

Backtracking — N-Queens

AlgorithmsBacktrackingRecursionMatrix

Place n queens on an n × n chessboard so that no two attack each other:
no two share a row, a column or a diagonal. Return the **number of
distinct placements**.

Place one queen per row, top to bottom. For each row, try every column that is
not attacked yet, and backtrack when a row has no safe column. Checking
"attacked" in O(1) is the whole trick: keep three sets, the used columns, the
used row - col diagonals and the used row + col anti-diagonals.

Examples

solve(4)  → 2
solve(1)  → 1
solve(3)  → 0
solve(8)  → 92

Constraints

  • 1 <= n <= 9

Sample tests

Test #1The classic 4x4 board
Input: [4]
Output: 2
Test #2A single queen
Input: [1]
Output: 1
Test #3No placement exists
Input: [3]
Output: 0