Algo Visualizer

Recursion & Backtracking

Visited/Checking
Placed Queen
Invalid / Error
Success Solutions
Debugger · v1.0
LIVE
1function solveNQUtil(col) {
2 // 1: Base Case
3 if (col >= N) return true;
4
5 // 2: Try placing queen in all rows one by one
6 for (let i = 0; i < N; i++) {
7 // 3: Check if queen can be placed here
8 if (isSafe(i, col)) {
9
10 // 4: Place queen
11 board[i][col] = QUEEN;
12
13 // 5: Recur for next columns
14 if (solveNQUtil(col + 1)) return true;
15
16 // 6: BACKTRACK - Remove Queen
17 board[i][col] = EMPTY;
18 }
19 }
20 // 7: Could not place return false
21 return false;
22}
Board:4x4
1x
Recursion & Backtracking

N-Queens Algorithm

Step 1 of 5

A classic combinatorial problem that demonstrates the power of recursive trial-and-error (Backtracking).

The Objective

Place N queens on an N×N board such that no two queens attack each other. This means no two queens can be in the same row, column, or diagonal.

Q
Queen
Under Attack