N-Queens
Arrange n queens on an n x n chessboard so that none of them attack one another — meaning no two queens may share a row, a column, or a diagonal. Return every distinct board arrangement that satisfies this.
Each returned solution is an array of strings, where 'Q' denotes a square holding a queen and '.' denotes an empty one.
Sample Input and Output
Example 1 · Run Sample
n = 4 [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] Example 2
n = 1 [["Q"]] - 1 <= n <= 9
Test Cases (2)
Place queens one row at a time using backtracking. Track which columns and diagonals are already attacked using sets. A queen at (row, col) occupies the row - col diagonal and the row + col anti-diagonal.
function solveNQueens(n) {
const result = [];
const cols = new Set();
const diag = new Set();
const antiDiag = new Set();
const board = Array.from({ length: n }, () => '.'.repeat(n));
function backtrack(row) {
if (row === n) {
result.push([...board]);
return;
}
for (let col = 0; col < n; col++) {
if (cols.has(col) || diag.has(row - col) || antiDiag.has(row + col)) continue;
cols.add(col);
diag.add(row - col);
antiDiag.add(row + col);
board[row] = board[row].substring(0, col) + 'Q' + board[row].substring(col + 1);
backtrack(row + 1);
cols.delete(col);
diag.delete(row - col);
antiDiag.delete(row + col);
board[row] = '.'.repeat(n);
}
}
backtrack(0);
return result;
}Time: O(n² × n!) as a loose upper bound including candidate checks and board-string construction. Space: O(n²) for the current board strings, plus O(n) for sets and recursion, excluding returned boards.
Saved in this browser only. Private to you.