function solveNQueens(n: number): string[][] {
const solutions: string[][] = [];
const queens: number[] = new Array(n).fill(-1);
function isValid(row: number, col: number): boolean {
for (let previousRow = 0; previousRow < row; previousRow++) {
const previousCol = queens[previousRow];
if (col === previousCol || Math.abs(row - previousRow) === Math.abs(col - previousCol)) {
return false;
}
}
return true;
}
function placeQueen(row: number): void {
if (row === n) {
const solution: string[] = queens.map(col => '.'.repeat(col) + 'Q' + '.'.repeat(n - col - 1));
solutions.push(solution);
return;
}
for (let col = 0; col < n; col++) {
if (isValid(row, col)) {
queens[row] = col;
placeQueen(row + 1);
queens[row] = -1;
}
}
}
placeQueen(0);
return solutions;
}