1.1. The 4-Queens Problem

We present here a well-known problem among Constraint Programming practitioners: the 4-Queens Problem. We shall encounter this problem again and generalize it in the Chapter Defining search primitives: the n-Queens Problem.

1.1.1. The problem

The 4-Queens Problem[1] consists in placing four queens on a 4 x 4 chessboard so that no two queens can capture each other. That is, no two queens are allowed to be placed on the same row, the same column or the same diagonal.

The following figure illustrates a solution to the 4-Queens Problem: none of the 4 queens can capture each other.

../../_images/sol_4x4_b.png

Although this particular problem isn’t very impressive, keep in mind that you can generalize it to n \times n chessboards with n \geqslant 4.

1.1.2. A mathematical translation of the problem

In Constraint Programming we translate a real problem into a mathematical model with variables and constraints. Variables represent decisions and constraints restrain the variables from taking arbitrary values. For instance, to model the 4-Queens Problem, we could use a binary variable x_{ij} that indicates if a queen is present on the given (i,j) square (x_{ij} = 1) or not (x_{ij} = 0). The first index i denotes the i^\text{th} row and the second index j the j^\text{th} column. We need several constraints to model that no two queens can capture each other. To limit the number of queens to 4, we can add the following constraint:

\sum_{(i,j) \in \, \textrm{squares}} x_{ij} = 4.

This constraint ensures that we place 4 queens on the chessboard. In general, constraints only permit possible combinations of values of variables corresponding to real solutions[2].

In the next section, we will see how the or-tools‘ CP solver tries to solve this problem. More precisely, how the solver will try to solve the model we will develop and explain in the sections The n-Queens Problem and Implementation of a basic model[3].