Algo-Sim › Recursion & Backtracking
N-Queens
Hard · Recursion & Backtracking · step through it in Java, Python and C++ on your own input
Place n queens so none attack: one queen per row, and prune every square whose column or diagonal is already taken.
Problem
Place n queens on an n × n chessboard so that no two share a row, a column or a diagonal. Return every distinct arrangement, drawing each board with Q for a queen and . for an empty square.
Constraints
- 1 ≤ n ≤ 9
- The search space shrinks fast with pruning; n = 9 has 352 solutions
Edge cases to test
- n = 1: one solution
- n = 2 and n = 3: none
- n = 8: 92 solutions
Follow-up questions
- How are diagonals checked in O(1)?
- Cells on one diagonal share
r − c, on the otherr + c; keep a set or boolean array for each. - What if you only need the count?
- Use bitmasks for columns and diagonals and count leaves: much faster, same search (LC 52).
Solution
Java
List<List<String>> result = new ArrayList<>();
List<List<String>> solveNQueens(int n) {
int[] queens = new int[n];
backtrack(n, 0, queens, new HashSet<>(), new HashSet<>(), new HashSet<>());
return result;
}
void backtrack(int n, int row, int[] queens, Set<Integer> cols, Set<Integer> diag, Set<Integer> anti) {
if (row == n) {
result.add(draw(queens, n));
return;
}
for (int c = 0; c < n; c++) {
if (cols.contains(c) || diag.contains(row - c) || anti.contains(row + c)) continue;
queens[row] = c;
cols.add(c); diag.add(row - c); anti.add(row + c);
backtrack(n, row + 1, queens, cols, diag, anti);
cols.remove(c); diag.remove(row - c); anti.remove(row + c);
}
}
List<String> draw(int[] queens, int n) {
List<String> board = new ArrayList<>();
for (int r = 0; r < n; r++) {
char[] line = new char[n];
Arrays.fill(line, '.');
line[queens[r]] = 'Q';
board.add(new String(line));
}
return board;
}Python
def solve_n_queens(n):
result = []
queens = [0] * n
cols, diag, anti = set(), set(), set()
def backtrack(row):
if row == n:
result.append(["." * q + "Q" + "." * (n - q - 1) for q in queens])
return
for c in range(n):
if c in cols or row - c in diag or row + c in anti:
continue
queens[row] = c
cols.add(c); diag.add(row - c); anti.add(row + c)
backtrack(row + 1)
cols.remove(c); diag.remove(row - c); anti.remove(row + c)
backtrack(0)
return resultC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<string>> result = {};
vector<vector<string>> solveNQueens(int n) {
vector<int> queens = vector<int>(n);
unordered_set<int> cols, diag, anti;
backtrack(n, 0, queens, cols, diag, anti);
return result;
}
void backtrack(int n, int row, vector<int> &queens, unordered_set<int> &cols, unordered_set<int> &diag, unordered_set<int> &anti) {
if (row == n) {
result.push_back(draw(queens, n));
return;
}
for (int c = 0; c < n; c++) {
if (cols.count(c) || diag.count(row - c) || anti.count(row + c))
continue;
queens[row] = c;
cols.insert(c);
diag.insert(row - c);
anti.insert(row + c);
backtrack(n, row + 1, queens, cols, diag, anti);
cols.erase(c);
diag.erase(row - c);
anti.erase(row + c);
}
}
vector<string> draw(vector<int> &queens, int n) {
vector<string> board = {};
for (int r = 0; r < n; r++) {
vector<char> line = vector<char>(n);
fill(line.begin(), line.end(), '.');
line[queens[r]] = 'Q';
board.push_back(string(line.begin(), line.end()));
}
return board;
}
};
More Recursion & Backtracking problems
- Fibonacci Number (Easy)
- Tower of Hanoi (Medium)
- Generate Parentheses (Medium)
- Subsets (Medium)
- Subsets II (Medium)
- Permutations (Medium)
- Permutations II (Medium)
- Combinations (Medium)
- Letter Combinations of a Phone Number (Medium)
- Combination Sum (Medium)
- Combination Sum II (Medium)
- Palindrome Partitioning (Medium)
- Restore IP Addresses (Medium)
- Word Break II (Hard)
- Remove Invalid Parentheses (Hard)
- Word Search (Medium)
- Sudoku Solver (Hard)