Practice › Recursion & Backtracking
All N-Queens Boards
Hard · Recursion & Backtracking · Asked at Amazon, Google, Microsoft, Apple
Place n queens on an n × n chessboard so that no two attack each other (same row, column or diagonal). Print every solution, one per line: the n rows of the board separated by single spaces, using Q for a queen and . for an empty square. List the solutions in order of the queen’s column in row 1, then row 2, and so on (the natural backtracking order). Print NONE if there is no solution.
Input
A single integer n.
Output
All boards, one per line, or NONE.
Constraints
- 1 ≤ n ≤ 8
Fill the board row by row, trying columns left to right. Keep three boolean arrays — used columns, used "row − col" diagonals and used "row + col" diagonals — so each check is O(1).
Example 1
Input
4
Output
.Q.. ...Q Q... ..Q. ..Q. Q... ...Q .Q..
Example 2
Input
1
Output
Q
Hints
- There is exactly one queen per row — place them row by row.
- A queen attacks along its column and both diagonals; cells on one diagonal share row − col (or row + col).
- Trying columns left to right gives the required order.
Approach
Backtrack over rows. For row r, try columns c = 0 … n − 1 that are free in cols[c], d1[r − c + n − 1] and d2[r + c]; mark them, recurse to row r + 1, then unmark. When all rows are placed, turn the column list into n strings of '.' with one 'Q' and print them on one line. If nothing was printed, print NONE (n = 2 and n = 3 have no solutions).
Complexity: O(n!) time in the worst case · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int n;
vector<int> col;
vector<bool> usedCol, d1, d2;
vector<string> boards;
void go(int r) {
if (r == n) {
string b;
for (int i = 0; i < n; i++) {
string row(n, '.');
row[col[i]] = 'Q';
b += (i ? " " : "") + row;
}
boards.push_back(b);
return;
}
for (int c = 0; c < n; c++) {
if (usedCol[c] || d1[r - c + n - 1] || d2[r + c]) continue;
usedCol[c] = d1[r - c + n - 1] = d2[r + c] = true;
col[r] = c;
go(r + 1);
usedCol[c] = d1[r - c + n - 1] = d2[r + c] = false;
}
}
int main() {
cin >> n;
col.assign(n, 0);
usedCol.assign(n, false);
d1.assign(2 * n, false);
d2.assign(2 * n, false);
go(0);
if (boards.empty()) cout << "NONE\n";
for (auto &b : boards) cout << b << "\n";
return 0;
}Python solution
n = int(input())
col = [0] * n
used_col = [False] * n
d1 = [False] * (2 * n)
d2 = [False] * (2 * n)
boards = []
def go(r):
if r == n:
boards.append(" ".join("." * c + "Q" + "." * (n - c - 1) for c in col))
return
for c in range(n):
if used_col[c] or d1[r - c + n - 1] or d2[r + c]:
continue
used_col[c] = d1[r - c + n - 1] = d2[r + c] = True
col[r] = c
go(r + 1)
used_col[c] = d1[r - c + n - 1] = d2[r + c] = False
go(0)
print("\n".join(boards) if boards else "NONE")Java solution
import java.util.*;
public class Main {
static int n;
static int[] col;
static boolean[] usedCol, d1, d2;
static StringBuilder out = new StringBuilder();
static void go(int r) {
if (r == n) {
for (int i = 0; i < n; i++) {
if (i > 0) out.append(' ');
for (int c = 0; c < n; c++) out.append(c == col[i] ? 'Q' : '.');
}
out.append('\n');
return;
}
for (int c = 0; c < n; c++) {
if (usedCol[c] || d1[r - c + n - 1] || d2[r + c]) continue;
usedCol[c] = d1[r - c + n - 1] = d2[r + c] = true;
col[r] = c;
go(r + 1);
usedCol[c] = d1[r - c + n - 1] = d2[r + c] = false;
}
}
public static void main(String[] args) {
n = new Scanner(System.in).nextInt();
col = new int[n];
usedCol = new boolean[n];
d1 = new boolean[2 * n];
d2 = new boolean[2 * n];
go(0);
System.out.print(out.length() == 0 ? "NONE\n" : out);
}
}