N-Queens – Solution & Complexity
Solution Walkthrough
Step 1: Recognize the Pattern
This is classic backtracking: place one queen per row, reject any column or diagonal conflict immediately, and let the recursion tree enumerate solutions in deterministic row-major DFS order.
Step 2: Build the Algorithm
Track three conflict sets or boolean arrays: used columns, used main diagonals (
row - col), and used anti-diagonals (row + col). For each row, try columns from0ton - 1; every valid placement recurses to the next row, and every complete placement becomes one output board.Step 3: Check Edge Cases
Handle the trivial
n = 1board, remember thatn = 2andn = 3have no solutions, and be careful to copy the constructed board when a solution is found so later backtracking does not mutate saved answers.Step 4: Solution and Complexity
Time:
O(n!)in the classic backtracking worst case. Space:O(n^2)counting the output boards plusO(n)recursion state and the current placement arrays.