Recursion & Backtracking · Pattern 2 of 9
N-Queens: place one queen per row
Every row holds exactly one queen, so place them row by row. Three boolean arrays for columns and both diagonals tell you in O(1) whether a square is safe.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Place n pieces on an n × n board so none attack each other
- Each row (or column) must hold exactly one item
- You need every valid board, not just one
The template
List<List<String>> solveNQueens(int n) {
List<List<String>> out = new ArrayList<>();
char[][] board = new char[n][n];
for (char[] row : board) Arrays.fill(row, '.');
place(0, board, new boolean[n], new boolean[2 * n], new boolean[2 * n], out);
return out;
}
void place(int r, char[][] board, boolean[] col, boolean[] diag, boolean[] anti, List<List<String>> out) {
int n = board.length;
if (r == n) { // every row has a queen
List<String> b = new ArrayList<>();
for (char[] row : board) b.add(new String(row));
out.add(b);
return;
}
for (int c = 0; c < n; c++) {
if (col[c] || diag[r - c + n] || anti[r + c]) continue; // attacked
col[c] = diag[r - c + n] = anti[r + c] = true;
board[r][c] = 'Q';
place(r + 1, board, col, diag, anti, out);
board[r][c] = '.'; // undo
col[c] = diag[r - c + n] = anti[r + c] = false;
}
} def solve_n_queens(n):
out, board = [], [['.'] * n for _ in range(n)]
col, diag, anti = set(), set(), set() # r - c and r + c name the diagonals
def place(r):
if r == n: # every row has a queen
out.append([''.join(row) for row in board])
return
for c in range(n):
if c in col or r - c in diag or r + c in anti:
continue # attacked
col.add(c); diag.add(r - c); anti.add(r + c)
board[r][c] = 'Q'
place(r + 1)
board[r][c] = '.' # undo
col.remove(c); diag.remove(r - c); anti.remove(r + c)
place(0)
return out void place(int r, vector<string>& board, vector<bool>& col, vector<bool>& diag, vector<bool>& anti, vector<vector<string>>& out) {
int n = board.size();
if (r == n) { out.push_back(board); return; } // every row has a queen
for (int c = 0; c < n; c++) {
if (col[c] || diag[r - c + n] || anti[r + c]) continue; // attacked
col[c] = diag[r - c + n] = anti[r + c] = true;
board[r][c] = 'Q';
place(r + 1, board, col, diag, anti, out);
board[r][c] = '.'; // undo
col[c] = diag[r - c + n] = anti[r + c] = false;
}
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> out;
vector<string> board(n, string(n, '.'));
vector<bool> col(n), diag(2 * n), anti(2 * n);
place(0, board, col, diag, anti, out);
return out;
} function solveNQueens(n) {
const out = [], board = Array.from({ length: n }, () => new Array(n).fill('.'));
const col = new Array(n).fill(false), diag = new Array(2 * n).fill(false), anti = new Array(2 * n).fill(false);
function place(r) {
if (r === n) { out.push(board.map(row => row.join(''))); return; } // every row has a queen
for (let c = 0; c < n; c++) {
if (col[c] || diag[r - c + n] || anti[r + c]) continue; // attacked
col[c] = diag[r - c + n] = anti[r + c] = true;
board[r][c] = 'Q';
place(r + 1);
board[r][c] = '.'; // undo
col[c] = diag[r - c + n] = anti[r + c] = false;
}
}
place(0);
return out;
} The variations
-
1One queen per row
The row is the depth of the recursion and the column is the choice. A square is safe when its column, its
r − cdiagonal and itsr + canti-diagonal are all unused.
Mistakes to avoid
r - ccan be negative: shift it bynbefore using it as an array index.- Scanning the whole board to check safety at every step: three arrays make the check O(1).
- Undoing the board but not the column and diagonal markers (or the other way round).
Mark it done once you can write the template from memory and you have solved the worked examples yourself.