Loading algorithms…

Loading visualizer…

Algorithms/Backtracking/N-Queens

N-Queens

Place N queens on an N×N board so none attack each other. The canonical backtracking example — try, conflict, undo, retry.

BacktrackingConstraint SatisfactionRecursion
6

4 total solutions exist for N=6 · showing the first search path

Step 1 of 1922: 6×6 board. Place one queen per row so no two share a column or diagonal. Starting from row 0.
1 / 1922
Speed

6×6 board. Place one queen per row so no two share a column or diagonal. Starting from row 0.

Queen columns per row

row 0—
row 1—
row 2—
row 3—
row 4—
row 5—
Solutions found so far
0
Total for N=6
4
n-queens.js
1function solve(row) {
2 if (row === N) {
3 solutions.push([...queens]);
4 return;
5 }
6 
7 for (let col = 0; col < N; col++) {
8 if (isSafe(row, col)) {
9 queens[row] = col; // place
10 solve(row + 1); // recurse
11 queens[row] = null; // undo
12 }
13 }
14}
15 
16function isSafe(r, c) {
17 return every placed queen q at (qr, qc)
18 has qc !== c
19 && |qr - r| !== |qc - c|;
20}

Slide N from 4 to 8 · Red ✕ marks attacked squares · Backtracking undoes dead ends automatically

About the N-Queens algorithm

Place N queens on an N×N board so none attack each other. The canonical backtracking example — try, conflict, undo, retry.

Category
Backtracking
Difficulty
Medium
Time complexity
O(N!)
Space complexity
O(N)
←Previous Algorithm
Segment Tree
Data StructuresO(log n) per op
Index→
All Algorithms
Browse complete interactive catalog