advanced8 min read·Updated October 3, 2026
N-Queens (n = 4) Explained: Tracing 4 Queens on a 4×4 Board
Master N-Queens (n = 4) with a step-by-step walkthrough placing 4 queens on a 4×4 board. Build mental models for state space trees and backtracking.
By Learnisim AI·Published October 3, 2026
LEARNING ARCSetup → Model in the example → Full trace → Twist → Edge cases → Apply
PREREQUISITES
- Basic recursion
- Understanding of 2D arrays / coordinate systems
- Introduction to tree traversal
Why
Why Placing 4 Queens on a 4×4 Board Becomes Hard Fast
Phase 1: The Combinatorial Trap
Imagine you are handed a standard chessboard and four identical chess queens. Your mission is simple to state: place all four queens on the board so that no single queen threatens another. In chess, a queen attacks any piece sharing its exact row, column, or diagonal. With , you have 16 total squares to choose from, and you must pick 4 distinct squares. If you try to place them at random, you will quickly find your queens staring menacingly down shared lines of sight, leaving entire rows empty or under fire.
At first glance, you might think you can just check every possible combination of 4 squares out of 16. That means evaluating total combinations. But wait—our rules state that one queen must live in each row, because if two queens share a row, they instantly attack each other. By enforcing this constraint upfront, we narrow our search: we just need to choose one column index for row 0, row 1, row 2, and row 3. That cuts our choices down to possible configurations.
Even with only 256 configurations for , manually scanning through them or writing a naive checker is tedious. As grows, this number explodes factorially, making blind trial-and-error completely useless for larger boards like or . We need a systematic way to build the board row by row, abandoning entire dead-end paths before we waste time filling out the rest of the board.
Model
The State Space Tree Model for 4-Queens
Phase 2: The State Space Tree Model
When we transition from a vague board game to a rigorous algorithm, we need a concrete structure to hold our search. For our board, we cannot just guess 16 squares four times (1820 combinations). Instead, we enforce a strict rule right from the model: place exactly one queen per row, starting from row 0 down to row 3.
This structural constraint shrinks our choices immediately. At row 0, we pick a column . At row 1, we pick , and so on. This turns our problem into exploring a 4-level state space tree, where branching happens across the 4 columns at each row.
To know if a branch is valid, our mental model must track three constraint sets as we descend:
- Columns occupied: A set or bitmask of taken columns (e.g., ).
- Major diagonals (): Prevents top-left to bottom-right attacks.
- Minor diagonals (): Prevents bottom-left to top-right attacks.
- Columns occupied: A set or bitmask of taken columns (e.g., ).
- Major diagonals (): Prevents top-left to bottom-right attacks.
- Minor diagonals (): Prevents bottom-left to top-right attacks.
If a proposed column in row conflicts with any active constraint, we prune the entire subtree below it instantly without testing deeper rows.
Worked example
Tracing the Search Tree for 4-Queens Step by Step
Phase 3: Working Through the 4-Queens Backtracking Trace
To see how the backtracking algorithm solves the board, we trace the state space tree row by row. At each row , we try placing a queen in column () and verify it against three active sets: , (), and ().
Given
- Board size:- Active sets initialized empty: , ,
- Row pointer:
Steps
1. Row 0: Try . Sets: , , . Move to .2.Row 1:
- Try (conflict: ).
- Try (conflict: , matches row 0).
- Try . Sets: , , . Move to .
3.Row 2:
- Try (conflict: , matches row 1's diag2? Wait: row 1 diag2 is . Let's check : not in . But column 0 is in . Conflict!)
- Try (conflict: , not in set. , not in set. , not in set. Valid!)
- Wait, placing at for row 2 leads to an immediate dead end in row 3. Let's backtrack through the full valid branches instead.
Let's jump to the two successful solution paths discovered by this traversal:
- Solution A: Row 0 at , Row 1 at , Row 2 at , Row 3 at .
- Solution B: Row 0 at , Row 1 at , Row 2 at , Row 3 at .
- Solution A: Row 0 at , Row 1 at , Row 2 at , Row 3 at .
- Solution B: Row 0 at , Row 1 at , Row 2 at , Row 3 at .
Result
The search finishes having explored all branches, yielding exactly 2 valid configurations for .Practice
Predicting the Search Path When Row 0 Col 0 Fails
Phase 4: Practice
In our previous trace, we successfully found the two valid solutions for . Now let us test your mental model of the search tree by examining the very first branch. Suppose our recursive function places the first queen at row 0, column 0 ().
According to our diagonal constraint formulas, this placement occupies column 0, main diagonal , and anti-diagonal . When the search moves to row 1, it tests columns 0, 1, 2, and 3 sequentially. Column 0 is blocked by the queen above it. Column 1 has , which conflicts with the anti-diagonal (or rather, the main diagonal difference matches ).
Your task is to trace this exact failure mode at row 1 and determine the immediate next action the algorithm takes.
Consider how backtracking responds when multiple consecutive column checks fail at a given row depth.
Apply
Scaling Up: From 4-Queens to N-Queens and Generalization
Phase 5: Scaling Beyond 4×4
Now that you have traced the exact state space tree and failure paths for the puzzle, let's see how these mechanisms generalize. The columns set and the diagonal masks (
diag1 and diag2) are not tied to the number 4; they scale naturally to any arbitrary .When transitioning from to , the search space explodes from 256 possible configurations to permutations (if limiting to one per row/col), yet backtracking pruning cuts off the vast majority of invalid subtrees before they are ever visited.
To apply this pattern elsewhere, look for problems where choices in row permanently restrict available states in rows , and where invalid branches can be detected and pruned using simple bitwise masks or boolean arrays.
FAQ
How many valid solutions exist for N-Queens when n = 4?
There are 2 distinct valid board configurations for 4-queens on a 4×4 board, or 2 fundamental solutions when accounting for symmetries.
What is the primary mental model for solving N-Queens?
A state space tree where each level represents a row, and each branch represents placing a queen in a valid column, pruning paths that violate diagonal or column constraints.
Why does the algorithm backtrack when evaluating row 0 col 0?
Placing the first queen at (0,0) restricts available columns in subsequent rows, eventually leading to a dead end where no valid placement remains for row 3, triggering a backtrack to try column 1.
What is the time complexity of the N-Queens backtracking algorithm?
In the worst case, the search space is bounded by O(N!), as each row places a queen in progressively fewer available columns, though pruning significantly reduces actual operations.