N-Queens Puzzle Solver (QUBO)

Place N queens on an N×N board so that no two attack each other. QUBO++ turns the puzzle into a QUBO model and its EasySolver searches for a placement in a few seconds.

Explained in the docs: C++ (QUBO++)· Python (PyQBPP)

8
10s
 

How to use

The demo runs on AWS Lambda with limited resources; QUBO++ on a desktop PC is several times faster.

How the puzzle becomes a QUBO model

QUBO (Quadratic Unconstrained Binary Optimization) asks for 0/1 values of variables that minimize a polynomial of degree at most 2. It is the problem format of quantum annealers and Ising machines; QUBO++ solves it on ordinary CPUs and GPUs. The demo uses one binary variable $x_{i,j}$ per square: $x_{i,j}=1$ if a queen is placed at row $i$ and column $j$. The polynomial to minimize is the sum of the following penalties.

Each penalty is 0 when its condition holds and positive otherwise, so the placements with value 0 are exactly the solutions of the puzzle. The queens you fix are substituted into the model before solving: their variables become 1 and the squares they attack become 0, which makes the model smaller.

The program

With PyQBPP, the Python version of QUBO++, the model above takes a few lines. This program prints a solution for $N=8$:

import pyqbpp as qbpp

n = 8
x = qbpp.var("x", shape=(n, n))

f = qbpp.sum(qbpp.vector_sum(x, axis=0) == 1) + \
    qbpp.sum(qbpp.vector_sum(x, axis=1) == 1)

m = 2 * n - 3
a = qbpp.expr(shape=m)
b = qbpp.expr(shape=m)

for i in range(m):
    k = i + 1
    for r in range(n):
        c = k - r
        if 0 <= c < n:
            a[i] += x[r][c]

    d = i - (n - 2)
    for r in range(n):
        c = r + d
        if 0 <= c < n:
            b[i] += x[r][c]

f += qbpp.sum((0 <= a) & (qbpp.same <= 1))
f += qbpp.sum((0 <= b) & (qbpp.same <= 1))

f.simplify_as_binary()

solver = qbpp.EasySolver(f)
sol = solver.search(target_energy=0)
for i in range(n):
    for j in range(n):
        print("Q" if sol(x[i][j]) == 1 else ".", end="")
    print()

The N-Queens page explains the program line by line; the C++ version is also available.

Run it on your computer

PyQBPP runs on Linux (x86-64 and ARM64) and on Windows through WSL:

pip install pyqbpp

See Installation for details, and the other demos for more problems solved with QUBO++.