N-Queens in TypeScript

function solveNQueens(n: number): string[][] {
    const solutions: string[][] = [];
    const queens: number[] = new Array(n).fill(-1); // Represents queen's column position in each row

    function isValid(row: number, col: number): boolean {
        for (let previousRow = 0; previousRow < row; previousRow++) {
            const previousCol = queens[previousRow];
            // Check for same column or diagonal conflict
            if (col === previousCol || Math.abs(row - previousRow) === Math.abs(col - previousCol)) {
                return false;
            }
        }
        return true;
    }

    function placeQueen(row: number): void {
        if (row === n) {
            // All queens are successfully placed, convert to solution format
            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);
                // Backtrack
                queens[row] = -1;
            }
        }
    }

    placeQueen(0);
    return solutions;
}

PrevNext