Repository navigation
🧩 Constraint Solving POTD:Problem of the Day: N-Queens #76498
Closed
Replies: 1 comment
|
This discussion has been marked as outdated by Constraint Solving — Problem of the Day. A newer discussion is available at Discussion #76840. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Problem Statement
Place
nqueens on ann × nchessboard so that no two queens attack each other. Queens attack along rows, columns, and both diagonals, so every row, every column, and every diagonal may hold at most one queen.Small instance (4×4): there are exactly two solutions, shown here as the column of the queen in each row (1-indexed):
(2, 4, 1, 3)(3, 1, 4, 2)Input: board size
n.Output: one (or all) placements that satisfy the constraints, or a proof that none exists.
Solution counts for
n = 1..10are1, 0, 0, 2, 10, 4, 40, 92, 352, 724. Up to the board's eight symmetries (rotations and reflections), 8-queens has only 12 distinct solutions.Why It Matters
alldifferentcaptures several families of pairwise conflicts at once.Modeling Approaches
1. Constraint Programming (one variable per row)
x_i ∈ {1..n}, the column of the queen in rowi. This gives onlynvariables.alldifferent(x),alldifferent(x_i + i), andalldifferent(x_i − i). These cover columns and both diagonal directions.n^nrather than2^(n2). Propagation ofalldifferentremoves many values early. The model is compact and scales well to dozens of queens.Example Model (Pseudo-code)
2. 0/1 Linear / SAT Encoding (one variable per cell)
b[i,j] ∈ {0,1}, 1 if a queen sits at rowi, columnj. This givesn2variables.Σ_j b[i,j] = 1for each row, andΣ ≤ 1over each column and each diagonal.O(n3)clauses in total. The LP relaxation is weak (fractional solutions are easy to find), so the solver relies on branching and clause learning rather than bounding. Expect this to scale worse than model 1.Key Techniques
alldifferentis usually filtered with generalized arc consistency using bipartite matching (Régin, 1994). This detects values that cannot appear in any solution, which prunes far more than pairwise≠constraints do.n. Min-conflicts (Minton et al., 1992) starts from a random placement and repeatedly moves a conflicting queen to the least-conflicting column in its row. It finds solutions for very large boards with little memory, which systematic search cannot match.Challenge Corner
nvariables and no diagonalalldifferent, using auxiliary variables instead? What does propagation look like?n = 8.ndoes a solution exist?References
alldifferent.All reactions