ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
NQueens.h File Reference

The \( n \) queens (exercise 16.5): \( n \) queens on an \( n \times n \) board, no two on a row, a column or a diagonal. More...

#include <bit>
#include "ADS/Contract.h"
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <stdexcept>
#include <string>
#include <vector>
#include "ADS/backtrack/impl/NQueens.tpp"

Go to the source code of this file.

Namespaces

namespace  ADS

Functions

template<class F>
long ADS::nQueens (int n, F &&f)
 the placements of \( n \le 32 \) queens, f( Q ) on each, \( Q[ r ] \) the column of the queen of the row \( r \), and true from f to stop; the number found
template<class F>
long ADS::nQueensIterative (int n, F &&f)
 the placements of \( n \) queens by the iterative backtracking, with the stage \( k \) and the column \( V[ k ] \) of the queen of the row \( k \), f( V ) on each and true from f to stop; the number found
bool ADS::admissible (const std::vector< int > &Q)
 whether no two queens of \( Q \) attack each other, \( Q[ r ] \) the column of the queen of the row \( r \)
std::string ADS::board (const std::vector< int > &Q)
 the board of \( Q \), a line per row, with the letter Q for a queen and a dot for an empty square

Detailed description

The \( n \) queens (exercise 16.5): \( n \) queens on an \( n \times n \) board, no two on a row, a column or a diagonal.

A row holds exactly one queen, and so the solution is the vector \( Q \) of their columns, a permutation: \( n! \) candidates instead of the \( 2^{n^2} \) placements; the backtrack prunes the columns and the two diagonals already taken, kept as masks of bits, so that a choice is checked in \( O( 1 ) \). The numbers of solutions are 1, 0, 0, 2, 10, 4, 40, 92, 352, 724 for \( n = 1 , \ldots , 10 \).

The contracts [see Contract.h]: \( 1 \le n \le 32 \), the solutions are admissible (checked at level 3), and board() needs a column of the board for each row. The operations are defined in NQueens.tpp.

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, exercise 16.5, https://algoritmicamente.it/materiali/libro/capitoli/cap16.pdf
J. Bell, B. Stevens, A survey of known results and research areas for n-queens, Discrete Mathematics 309(1), 1-31, 2009, doi:10.1016/j.disc.2007.12.043
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa