Home
DSA Visualizer
Backtracking
N-Queens
N-Queens
The N-Queens puzzle is the problem of placing N chess queens on an N×N chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal.
READY
Backtracks
0
6 queens, one per row. No two may share a column or a diagonal.
Next
Try a queen at (0, 0).
Board
Intuition
We place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. If we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes, then we backtrack and return false.
Concept
Strategy: place one queen per column, left to right, and undo a placement the moment it leads nowhere.
- If every column already has a queen, the board is a solution.
- Otherwise take the next empty column and try each row in turn.
- Skip any row where the new queen would share a row or a diagonal with a queen already placed. Columns never clash, because each column gets exactly one queen.
- On a safe row, place the queen and solve the remaining columns recursively.
- If that recursive call fails, remove the queen and try the next row.
- If no row in this column works, report failure to the column before it, which then moves its own queen.
How it Works
- Define
backtrack(col). - Base Case: If
col == N, solution found. - Loop through rows
rowfrom 0 to N-1. - Check if placing queen at
(row, col)is safe (check row and diagonals). (Note: We check previous columns). - If safe: Place queen, call
backtrack(col + 1). - If recursive call returns (backtracks): Remove queen and try next row.
Step-by-Step Breakdown
Example: N=4
- Place Q at (0,0).
- Try (1,0) - Attack. (1,1) - Attack. (1,2) - Safe. Place Q.
- Try (2,0)...(2,3) - All attacked. Backtrack.
- Remove Q from (1,2). Try (1,3) - Safe. Place Q.
- ...and so on until a valid arrangement is found.
When to Use
- Constraint satisfaction problems.
- Scheduling problems with hard constraints.
When NOT to Use
- When an approximate solution is sufficient (simulated annealing might be faster for large N).
How to Identify
"Place N items such that they don't conflict", "Constraint satisfaction".
Applying for software engineering roles? Free, no sign-up:
AI resume checker — match your resume to the job description
Compare its cost with every other algorithm in the Big O cheat sheet.
