The N-Queens problem is one of the most classic puzzles in computer science: place N queens on an N×N chessboard such that no two queens threaten each other. This means no two queens can share the same row, column, or diagonal. Backtracking is the perfect fit for this kind of constraint-satisfaction problem — it explores every possibility depth-first, pruning dead-end paths early so we never waste time on positions already known to be invalid. This browser-based implementation lets you type any N between 4 and 13, click a button, and instantly see up to four valid solutions rendered as interactive visual chess boards with the ♛ queen symbol.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/HotCode2025/Print-Estoy-Cansado-Jefe-TercerSemestre/llms.txt
Use this file to discover all available pages before exploring further.
The Algorithm
The entire solver lives inside theresolver() function, which is triggered when the user clicks the button. It reads n from the input, initialises an N×N board filled with '.' characters, and defines two inner helper functions — esValido() and backtrack() — as closures that share access to n, tablero, and resultados. It then kicks off the search by calling backtrack(0).
resolver() — entry point with nested helpers
esValido and backtrack are declared inside resolver(). They close over n, tablero, and resultados, so no data needs to be passed as extra arguments.
The Validity Check — esValido(fila, col)
Before placing a queen on (fila, col), the algorithm verifies three independent constraints against all previously placed queens (rows 0 through fila - 1):
esValido(fila, col) — three-direction check
| Check | Direction | Logic |
|---|---|---|
| Column | ↑ straight up | same col, i from 0 to fila - 1 |
| Left diagonal | ↖ up-left | i-- and j-- until out of bounds |
| Right diagonal | ↗ up-right | i-- and j++ until out of bounds |
The Backtracking Flow
Place and recurse
For each column in the current row, call
esValido(). If it passes, mark the cell 'Q' and call backtrack(fila + 1) to advance to the next row.Base case reached
When
fila === n, every row has exactly one queen with no conflicts. Serialize the board with tablero.map(r => r.join('')) and push it into resultados.Backtrack on dead ends
If no column in the current row is valid, the function returns without finding a solution. The caller resets its own cell back to
'.' and tries the next column — this is the backtrack step.Rendering the Board
Once all solutions have been collected, the solver builds a visual HTML grid for each solution. Each row of the serialized board string is split into individual cell characters, and a<div class="celda"> is created for each one. If the character is "Q", the queen symbol is injected via innerHTML:
Rendering solutions as HTML grids
nth-child selectors to apply the alternating dark/light chessboard pattern automatically — no extra JavaScript required for styling.
Input Validation
The solver validatesn immediately before running. Values outside the range 4–13 are rejected with a styled error message rendered directly into the #soluciones container:
Input validation
Randomising the Output
When the total number of solutions exceeds four, the solver picks four at random using an elegant one-liner sort trick before slicing:Random selection when solutions > 4
Math.random() returns a value in [0, 1), so 0.5 - Math.random() randomly produces a positive or negative comparator, effectively shuffling the array. Slicing the first four elements then gives a random subset of solutions to display — different every time you click.
The number of valid N-Queens solutions grows exponentially with N. For reference: N=4 has 2 solutions, N=8 has 92, N=10 has 724, and N=13 has 73,712. The backtracking algorithm finds them all in milliseconds for these sizes, but complexity becomes impractical well above N=15.
Key Concepts
| Concept | How it’s used |
|---|---|
| Closures | esValido and backtrack are inner functions inside resolver(), sharing n, tablero, and resultados without extra parameters |
| Recursion | backtrack(fila + 1) advances row-by-row, unwinding when a dead end is reached |
| Backtracking | tablero[fila][col] = '.' resets the cell after a failed branch |
| Board as 2D array | Array(n).fill().map(() => Array(n).fill('.')) creates a clean N×N grid |
| Solution accumulation | Every time fila === n, the current board state is pushed into resultados |
| Constraint pruning | esValido() eliminates invalid positions before recursing, cutting the search space dramatically |