Algorithms · Visualized
N-Queens
Backtracking
Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.
Place N chess queens on an N×N board so that no two queens attack each other (no shared row, column, or diagonal). Time: O(N!) roughly, heavily pruned by safety checks average, O(N!) worst; space: O(N) — recursion depth and board state tracking.
Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.
N-Queens
BacktrackingPlace N chess queens on an N×N board so that no two queens attack each other (no shared row, column, or diagonal). Backtracking places queens one row at a time: for each row, try every column, check if it's safe given previously placed queens, and backtrack if no column works.
How N-Queens Works
- Process the board one row at a time, starting at row 0.
- For the current row, try placing a queen in each column one by one.
- Check if this placement is safe: no other queen already placed shares this column or either diagonal.
- If safe, place the queen and recurse to solve the next row.
- If all rows are filled, record this as a valid solution; if a row has no safe column, backtrack — remove the last placed queen and try the next column in the previous row.
N-Queens Worked Example
Input: 4
Row0: place queen at col1. Row1: col0,col2,col3 all attacked → dead end, backtrack row0 to col2. Row1: col0 safe → place. Row2: col1,col2,col3 attacked... eventually col? none safe → backtrack. Continue searching; for N=4 the two valid solutions found are queens at columns [1,3,0,2] and [2,0,3,1].
def n_queens(n):
cols, d1, d2 = set(), set(), set()
out, board = [], [['.'] * n for _ in range(n)]
def place(r):
if r == n:
out.append([''.join(row) for row in board])
return
for c in range(n):
if c in cols or r - c in d1 or r + c in d2:
continue
cols.add(c); d1.add(r - c); d2.add(r + c)
board[r][c] = 'Q'
place(r + 1)
board[r][c] = '.'
cols.remove(c); d1.remove(r - c); d2.remove(r + c)
place(0)
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
N-Queens Time & Space Complexity
When to Use N-Queens
- A classic constraint-satisfaction problem showcasing pruning in backtracking (checking safety before recursing, not after).
- Techniques generalize to any placement problem with row/column/region exclusion rules, like Sudoku solvers.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.