8 Queens Problem in JavaScript - Interactive Solution

A complete JavaScript guide to solving the 8 queens problem. Browser-ready code, Node.js compatibility, DOM integration techniques, and visualization tips. Or skip the code and try the live interactive puzzle.

Setup & Overview

JavaScript is uniquely positioned for the 8 queens problem because the same code runs in Node.js (for algorithmic work) and in the browser (for interactive visualization). You do not need any framework or library — vanilla ES6 is sufficient.

The algorithm used is backtracking: place one queen per row, check conflicts, recurse to the next row, and undo placements that lead to dead ends. For n=8 this finds all 92 solutions in well under a millisecond.

Want to see the result instead of writing code? Try the live interactive 8 queens puzzle — it visualizes queen placement in real time.

Live Interactive Puzzle

Place queens on the board yourself and get instant conflict feedback. Supports board sizes from 4x4 to 15x15.

View All 92 Solutions

Browse all 92 distinct solutions to the 8 queens problem with board diagrams.

Complete JavaScript Implementation

The following script works in both Node.js (node queens.js) and directly in a browser <script> tag:

/**
 * 8 Queens Problem - JavaScript Implementation
 * Works in Node.js and modern browsers.
 * No external dependencies required.
 */

function isSafe(board, row, col) {
    for (let i = 0; i < row; i++) {
        if (board[i] === col) return false;
        if (Math.abs(board[i] - col) === Math.abs(i - row)) return false;
    }
    return true;
}

function solveNQueens(n) {
    const solutions = [];
    const board = new Array(n).fill(-1);

    function backtrack(row) {
        if (row === n) {
            solutions.push([...board]);
            return;
        }
        for (let col = 0; col < n; col++) {
            if (isSafe(board, row, col)) {
                board[row] = col;
                backtrack(row + 1);
                board[row] = -1;
            }
        }
    }

    backtrack(0);
    return solutions;
}

function boardToString(solution) {
    const n = solution.length;
    return solution.map((col, row) => {
        return Array.from({ length: n }, (_, c) => c === col ? "Q" : ".").join(" ");
    }).join("\n");
}

// Run and display results
const solutions = solveNQueens(8);
console.log(`Total solutions: ${solutions.length}`);  // 92
console.log("\nFirst solution:");
console.log(boardToString(solutions[0]));

Browser Integration

To display solutions in a web page, call solveNQueens(8) and render results to the DOM. Here is a minimal HTML + JS example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>8 Queens Solver</title>
    <style>
        .board { display: inline-grid; border: 2px solid #333; margin: 8px; }
        .cell { width: 36px; height: 36px; display: flex; align-items: center;
                justify-content: center; font-size: 20px; }
        .cell.light { background: #f0d9b5; }
        .cell.dark  { background: #b58863; }
        #count { font-family: sans-serif; margin: 16px; font-size: 1.1rem; }
    </style>
</head>
<body>
    <div id="count"></div>
    <div id="boards"></div>

    <script>
    function isSafe(board, row, col) {
        for (let i = 0; i < row; i++) {
            if (board[i] === col) return false;
            if (Math.abs(board[i] - col) === Math.abs(i - row)) return false;
        }
        return true;
    }

    function solveNQueens(n) {
        const solutions = [];
        const board = new Array(n).fill(-1);
        function backtrack(row) {
            if (row === n) { solutions.push([...board]); return; }
            for (let col = 0; col < n; col++) {
                if (isSafe(board, row, col)) {
                    board[row] = col;
                    backtrack(row + 1);
                    board[row] = -1;
                }
            }
        }
        backtrack(0);
        return solutions;
    }

    function renderBoard(solution) {
        const n = solution.length;
        const grid = document.createElement("div");
        grid.className = "board";
        grid.style.gridTemplateColumns = `repeat(${n}, 36px)`;
        for (let r = 0; r < n; r++) {
            for (let c = 0; c < n; c++) {
                const cell = document.createElement("div");
                cell.className = "cell " + ((r + c) % 2 === 0 ? "light" : "dark");
                if (solution[r] === c) cell.textContent = "♛";
                grid.appendChild(cell);
            }
        }
        return grid;
    }

    const solutions = solveNQueens(8);
    document.getElementById("count").textContent =
        `Found ${solutions.length} solutions for the 8 Queens problem.`;

    // Only render first 10 to avoid overwhelming the page
    const container = document.getElementById("boards");
    solutions.slice(0, 10).forEach(s => container.appendChild(renderBoard(s)));
    </script>
</body>
</html>

Visualization Tips

To build a polished interactive visualization like the one on the play page, consider these techniques:

  • CSS Grid for the board: display: grid; grid-template-columns: repeat(8, 1fr); creates a perfect 8×8 layout without any JavaScript layout calculations.
  • Animate the backtracking: Use async/await with setTimeout delays to step through the algorithm visually. Store a queue of state transitions and replay them.
  • Highlight conflicts: After each queen placement, recheck all queens and add a CSS class (e.g., conflict) to attacking pairs. Instant visual feedback helps learners understand why certain placements fail.
  • Web Workers for large n: Running the solver for n≥12 on the main thread will freeze the UI. Move the algorithm to a Web Worker: const worker = new Worker('queens-worker.js'). Post messages back to the main thread with each solution found.
  • Canvas rendering: For displaying all 92 solutions simultaneously, a <canvas> element is more performant than 92 DOM grids. Draw each board programmatically using ctx.fillRect and ctx.fillText.

The interactive puzzle on this site combines all these techniques — try it now to see what is possible with vanilla JavaScript.

Preguntas Frecuentes

Does the JavaScript 8 queens solution work in the browser without Node.js?

Yes. The core solveNQueens function uses only standard ES6 features (arrow functions, spread operator, Array methods) that are supported in all modern browsers. Simply place the code in a <script> tag and call solveNQueens(8) from the browser console or from your page code.

How do I visualize the 8 queens algorithm step by step in JavaScript?

Instrument the backtracking function to record each state change (queen placed / queen removed). Store these as an array of snapshots, then replay them with setInterval or requestAnimationFrame, updating the DOM board at each step. This creates an animated visualization of the backtracking process.

Can I use the JavaScript solver for large board sizes (n > 10)?

For n > 12, move the solver to a Web Worker to avoid freezing the UI thread. For even better performance, use the bitwise optimization described in the backtracking guide. JavaScript's 32-bit bitwise operators support n up to 30.