Place n queens on an n×n chessboard so that no two attack each other (same row, column or diagonal). Return every distinct board, with 'Q' for a queen and '.' for an empty square.
Every cell on a '\' diagonal shares r − c, and every cell on a '/' diagonal shares r + c. Keep three sets so the attack check is O(1).
1function solveNQueens(n: number): string[][] {2const res: string[][] = [], queens: number[] = [];3const cols = new Set<number>(), diag = new Set<number>(), anti = new Set<number>();4function place(r: number) {5if (r === n) { res.push(queens.map((c) => ".".repeat(c) + "Q" + ".".repeat(n - c - 1))); return; }6for (let c = 0; c < n; c++) {7if (cols.has(c) || diag.has(r - c) || anti.has(r + c)) continue;8queens.push(c); cols.add(c); diag.add(r - c); anti.add(r + c);9place(r + 1);10queens.pop(); cols.delete(c); diag.delete(r - c); anti.delete(r + c);11}12}13place(0);14return res;15}
| Q | |||
Place at (0, 0).
Space: play/pause · ←/→: step