CoursifyCoursify

N-Queens Backtracking Pseudocode: A Comprehensive Explanation

N-Queens Backtracking Pseudocode: A Comprehensive Explanation

Verified Sources
May 26, 2026

The N-Queens problem asks us to place NN queens on an N×NN \times N chessboard such that no two queens share the same row, column, or diagonal.2 A standard solution strategy is backtracking, which incrementally builds a partial arrangement, tests whether the latest placement is valid, and abandons any branch as soon as it violates the constraints.2

A compact way to represent a candidate solution is a one-dimensional array QQ where Q[r]=cQ[r] = c means “the queen in row rr is placed in column cc.” This works because the algorithm places exactly one queen per row, so the remaining checks are only for column and diagonal conflicts.2

A square (r,c)(r,c) is unsafe if either:

  • some earlier queen already uses column cc, or
  • some earlier queen lies on the same diagonal, which occurs when the row distance equals the column distance:
Q[i]c=ir|Q[i] - c| = |i - r|

for some previously filled row ii.2

The backtracking search is naturally a depth-first traversal of a recursion tree: each level corresponds to one row, each branch corresponds to a column choice, and dead ends are pruned immediately when no legal column exists.

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation. 2 3 4 5

  2. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity. 2

  3. The N-queens Problem - Google OR-Tools - Constraint view of rows, columns, diagonals, and propagation/backtracking intuition.

  4. Algorithm of N queens - Stack Overflow - Clear explanation of recursive placement, backtracking behavior, and diagonal conflict logic.

N-Queens - Backtracking - Leetcode 51 - Python

Core Insight

Backtracking does not blindly enumerate all boards. It places queens row by row and prunes any partial arrangement as soon as a conflict appears.2

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

  2. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity.

Problem structure and why backtracking fits

The problem has a strong constraint structure: each queen restricts future placements in its column and along two diagonals.2 Because a partial arrangement can already be known invalid before all rows are filled, backtracking is especially effective: it avoids exploring completions of impossible prefixes.2

There are two common pseudocode styles:

  1. Naive safety check
    For each candidate (r,c)(r,c), scan all previously placed queens and test column and diagonal conflicts.

  2. Optimized safety check with auxiliary arrays
    Maintain three Boolean structures:

    • cols[c] for used columns
    • diag1[r - c + n - 1] for one diagonal family
    • diag2[r + c] for the other diagonal family

The optimized form preserves the same backtracking logic but reduces each safety test to O(1)O(1) time instead of scanning earlier rows.

A useful mathematical characterization is that queens share a diagonal exactly when either r+cr+c is equal or rcr-c is equal. This is why diagonal occupancy can be stored with indexed arrays.2

ConstraintConflict conditionFast representation
Same rowavoided by constructionone recursive level per row
Same columnanother queen already in column cccols[c]
Main diagonalsame value of rcr-cdiag1[r-c+n-1]
Anti-diagonalsame value of r+cr+cdiag2[r+c]

Footnotes

  1. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity. 2 3 4

  2. Algorithm of N queens - Stack Overflow - Clear explanation of recursive placement, backtracking behavior, and diagonal conflict logic. 2 3

  3. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation. 2

  4. The N-queens Problem - Google OR-Tools - Constraint view of rows, columns, diagonals, and propagation/backtracking intuition.

Backtracking pseudocode walkthrough

  1. 1
    Step 1

    Create an array Q[1..n] to store the chosen column for each row. Begin recursion at the first row with no queens placed yet.

    Footnotes

    1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

  2. 2
    Step 2

    At recursive level r, the algorithm assumes rows 1 through r-1 already contain a legal partial solution.

    Footnotes

    1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

  3. 3
    Step 3

    Loop through candidate columns 1 to n for the current row. Each candidate represents one possible branch in the search tree.2

    Footnotes

    1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

    2. The N-queens Problem - Google OR-Tools - Constraint view of rows, columns, diagonals, and propagation/backtracking intuition.

  4. 4
    Step 4

    Reject a candidate if it shares a column with a previous queen or if |Q[i] - c| = |i - r| for any earlier row i.2

    Footnotes

    1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

    2. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity.

  5. 5
    Step 5

    If the candidate is safe, store Q[r] = c. In the optimized version, also mark the corresponding column and diagonal arrays as occupied.

    Footnotes

    1. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity.

  6. 6
    Step 6

    Call the same procedure for row r + 1. This extends the current partial solution by one queen.

    Footnotes

    1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

  7. 7
    Step 7

    If r exceeds n, all queens have been placed legally, so output or store the current configuration.2

    Footnotes

    1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

    2. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity.

  8. 8
    Step 8

    After returning from recursion, remove the queen from the current row and unmark any occupancy structures so other columns can be tested. This is the essence of backtracking.2

    Footnotes

    1. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity.

    2. The N-queens Problem - Google OR-Tools - Constraint view of rows, columns, diagonals, and propagation/backtracking intuition.

Canonical pseudocode

A classical row-wise version is shown below. It mirrors the recursive formulation used in algorithm texts.

1procedure PlaceQueens(Q, r, n): 2 if r = n + 1: 3 output Q 4 return 5 6 for c = 1 to n: 7 legal = true 8 9 for i = 1 to r - 1: 10 if Q[i] = c: 11 legal = false 12 else if abs(Q[i] - c) = abs(i - r): 13 legal = false 14 15 if legal: 16 Q[r] = c 17 PlaceQueens(Q, r + 1, n)

This pseudocode means:

  • Q[r] = c stores the queen position for row r.
  • The inner loop checks all previously placed queens only, because future rows are still empty.
  • If no legal column exists for the current row, the function simply returns, and control goes back to the previous recursive call. That return is the “backtrack” step.2

An equivalent optimized pseudocode uses occupancy arrays:

1procedure Solve(row): 2 if row = n: 3 output current placement 4 return 5 6 for col = 0 to n - 1: 7 if cols[col] or diag1[row - col + n - 1] or diag2[row + col]: 8 continue 9 10 place queen at (row, col) 11 cols[col] = true 12 diag1[row - col + n - 1] = true 13 diag2[row + col] = true 14 15 Solve(row + 1) 16 17 remove queen at (row, col) 18 cols[col] = false 19 diag1[row - col + n - 1] = false 20 diag2[row + col] = false

This version is often preferred in implementations because the state needed for legality checks can be updated and reverted in constant time.

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation. 2 3 4

  2. The N-queens Problem - Google OR-Tools - Constraint view of rows, columns, diagonals, and propagation/backtracking intuition.

  3. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity.

Common Pseudocode Mistake

Do not say the algorithm 'moves queens around the board' arbitrarily. In standard backtracking, it commits to one row at a time, and when a branch fails, it returns to the previous row to try the next column.2

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

  2. The N-queens Problem - Google OR-Tools - Constraint view of rows, columns, diagonals, and propagation/backtracking intuition.

1for each column in current row: 2 scan all earlier rows 3 if no column or diagonal conflict: 4 place queen 5 recurse 6 remove queen

How backtracking behaves on a 4-queens example

For n=4n=4, one solution is [2,4,1,3][2,4,1,3], meaning queens are placed at:

(1,2),(2,4),(3,1),(4,3)(1,2), (2,4), (3,1), (4,3)

This is a valid configuration because no two positions share a column, and for every pair of queens, the absolute row difference is not equal to the absolute column difference.2

A simplified execution sketch:

  1. Try row 1, column 1.
  2. Explore row 2 possibilities.
  3. If row 3 cannot be filled legally, return to row 2 and try its next column.
  4. If row 2 exhausts all columns, return to row 1 and try row 1, column 2.
  5. Continue until a full arrangement is found.2

This illustrates the search principle: partial solutions are expanded only while they remain legal.

For n=2n=2 and n=3n=3, no solutions exist, so the backtracking tree is fully explored and every branch eventually fails. For n=1n=1, a single queen is trivially a solution.

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation. 2 3

  2. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity. 2 3

  3. The N-queens Problem - Google OR-Tools - Constraint view of rows, columns, diagonals, and propagation/backtracking intuition.

Backtracking search lifecycle for N-Queens

Empty board

Stage 1

Start with no queens placed and the first row selected for exploration."

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

Generate candidates

Stage 2

Enumerate every column in the current row as a candidate move."

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

Prune illegal choices

Stage 3

Discard any placement that duplicates a used column or diagonal.2"

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

  2. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity.

Descend recursively

Stage 4

Commit a legal placement and solve the next row."

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

Backtrack

Stage 5

If a deeper row has no legal move, undo the latest placement and continue searching.2"

Footnotes

  1. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity.

  2. The N-queens Problem - Google OR-Tools - Constraint view of rows, columns, diagonals, and propagation/backtracking intuition.

Emit solution

Stage 6

When all rows are filled, output the current queen positions as one valid solution.2"

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

  2. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity.

Time and space complexity

The worst-case time complexity is commonly described as O(n!)O(n!) for the backtracking formulation, because the algorithm places one queen per row and the number of feasible column choices shrinks as rows are filled; pruning prevents unrestricted nnn^n growth in the usual row-wise formulation.2 However, the exact number of explored nodes depends heavily on how early conflicts are detected and on the value of nn.2

There is also an important implementation distinction:

  • Naive safety scan
    Each candidate may require checking up to r1r-1 earlier queens, so the constant factors are larger.

  • Hashed/array-based safety check
    Column and diagonal occupancy tests become O(1)O(1) per candidate, improving practical speed while keeping the same exponential search structure.

Typical auxiliary space is:

  • O(n)O(n) for the recursion stack and the placement/occupancy arrays in the optimized variant,
  • or O(n2)O(n^2) if an explicit board matrix is stored in a simple implementation.

Footnotes

  1. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity. 2 3 4 5

  2. Time complexity of N Queen using backtracking? - Stack Overflow - Discussion supporting the common O(n!)O(n!) worst-case characterization. 2

  3. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

Implementation trade-offs in N-Queens backtracking

Relative comparison of common formulations

Key clarifications and edge cases

Exam-Ready Explanation

When explaining the pseudocode, say: choose a column, check column and diagonal safety, recurse to the next row, and undo the choice if the branch fails. That captures the essence precisely.2

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation.

  2. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity.

Final interpretation of the pseudocode

The N-Queens backtracking pseudocode is best understood as a recursive search over partial solutions.2 At row rr, the algorithm tries every column, keeps only placements consistent with rows 11 through r1r-1, and recursively solves the smaller subproblem for row r+1r+1. If no candidate works, the function returns to its caller, effectively undoing the previous decision and exploring a different branch.2

In conceptual terms, the pseudocode embodies three ideas:

  1. Constructive search: build a solution one row at a time.
  2. Constraint checking: reject illegal partial states immediately.2
  3. Systematic reversal: undo choices and continue until all possibilities are exhausted or a desired solution is found.2

That is exactly why N-Queens is considered a canonical example of backtracking in algorithm design.2

Footnotes

  1. Backtracking (University of Illinois CS473 notes) - Classical N-Queens backtracking pseudocode and recursion-tree interpretation. 2 3 4 5 6

  2. The N-queens Problem - Google OR-Tools - Constraint view of rows, columns, diagonals, and propagation/backtracking intuition. 2 3

  3. N Queen Problem - GeeksforGeeks - Backtracking approaches, optimized hashing arrays, and stated complexity. 2

  4. Algorithm of N queens - Stack Overflow - Clear explanation of recursive placement, backtracking behavior, and diagonal conflict logic.

Knowledge Check

Question 1 of 5
Q1Single choice

What does Q[r] = c mean in standard N-Queens pseudocode?

Explore Related Topics

1

Solving the Recurrence $T(n)=T(n-1)+n$ by Substitution Method

The course shows how to solve the decrease‑by‑one recurrence (T(n)=T(n-1)+n) (with (T(1)=1)) using the substitution method.

  • Repeatedly substitute (T(n-i)=T(n-i-1)+(n-i)) until reaching the base case, yielding (T(n)=T(1)+2+3+\dots+n).
  • The resulting sum is the triangular number (\frac{n(n+1)}{2}).
  • The dominant term (\frac{1}{2}n^{2}) gives a tight asymptotic bound (\Theta(n^{2})).
  • For recurrences of the form (T(n)=T(n-1)+f(n)), expanding to a summation quickly reveals the closed form.
2

Introduction to Randomized Algorithms

3

Converting the Regular Expression $(a+b)^*ab$ into an NFA

The course shows how to turn the regular expression (a+b)ab(a+b)^*ab—the set of all strings over {a,b}\{a,b\} that end with “ab”—into an NFA, first via Thompson’s systematic ε‑construction and then with a minimal three‑state NFA.

  • Thompson’s construction builds ε‑transitions for symbols aa, bb, their union, the Kleene star, and the final concatenations, yielding a 12‑state ε‑NFA.
  • A compact direct NFA uses only three states: q0q_0 loops on a,ba,b, branches on aa to q1q_1, and q1q_1 moves on bb to accepting q2q_2.
  • The compact NFA’s transition table illustrates nondeterministic moves (e.g., δ(q0,a)={q0,q1}δ(q_0,a)=\{q_0,q_1\}) and accepts exactly the strings ending in “ab”.
  • State‑complexity comparison: Thompson’s method needs many states and ε‑moves, while the direct NFA is far smaller and easier to simulate.
Chat with Kiro