![]() | |||||||||||
| |||||||||||
Python notebooks Description Python notebooks available in the GitHub repository python-notebooks.
Source Files By clicking on a file name, a preview is opened at the bottom of this page. n_queens.ipynb { "cells": [ { "cell_type": "markdown", "id": "78bbb5f2", "metadata": {}, "source": [ "# **The problem of the $n$ queens**" ] }, { "cell_type": "markdown", "id": "5189d5a2", "metadata": {}, "source": [ "***n_queens.ipynb***\n", "\n", "The $n$ queens problem: place $n$ queens on an $n \\times n$ chessboard so that none of them can be captured by another queen in one move.\n", "\n", "© Copyright 2025 Fair Isaac Corporation\n", "\n", "Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n", " \n", "Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n", "\n", "This example uses FICO® Xpress software. By running it, you agree to the Community License terms of the [Xpress Shrinkwrap License Agreement](https://community.fico.com/s/contentdocument/06980000002h0i5AAA) with respect to the FICO® Xpress software. See the [licensing options](https://www.fico.com/en/fico-xpress-trial-and-licensing-options) overview for additional details and information about obtaining a paid license." ] }, { "cell_type": "code", "execution_count": null, "id": "2a8311f0", "metadata": {}, "outputs": [], "source": [ "# Install the xpress package\n", "%pip install -q xpress" ] }, { "cell_type": "markdown", "id": "d18e2faf", "metadata": {}, "source": [ "## Problem description and formulation" ] }, { "cell_type": "markdown", "id": "7626db57", "metadata": {}, "source": [ "In the game of chess, the queen can move in a straight line horizontally, vertically, or diagonally any number of fields. The problem consists of finding the placement of as many queens as possible on an $n\\times n$ chessboard so that no queen can capture another in a single move.\n", "\n", "<p align=\"center\">\n", " <img src=\"https://upload.wikimedia.org/wikipedia/commons/2/2c/Eight_Queens12_positions.gif\" alt=\"Image (from Wikipedia)\"/>\n", "</p>\n", "\n", "This problem can be cast as an optimization problem where we try to maximize the number of queens placed on an $n\\times n$ chessboard. An upper bound is clearly $n$ as there cannot be more queens than rows (or columns). The problem has one yes/no decision variable for each cell, so we need $n^2$ **binary** variables, hereby denoted by $place_{ij}, \\forall i,j \\in \\mathcal{N}$. Note that $n$ is just a parameter and it can be set arbitrarily high, and $\\mathcal{N} = \\{1,..,n\\}$.\n", "\n", "$$\n", "\\max \\sum_{i,j \\in \\mathcal{N}} place_{i,j}$$\n", "\n", "Subject to:\n", "\n", "* At most one queen in each row:\n", "$$\\sum_{j \\in \\mathcal{N}} place_{i,j} \\leq 1, \\qquad \\forall i \\in \\mathcal{N}$$\n", "\n", "* At most one queen in each column:\n", "$$\\sum_{i \\in \\mathcal{N}} place_{i,j} \\leq 1, \\qquad \\forall j \\in \\mathcal{N}$$\n", "\n", "* At most one queen on every diagonal (north-east and north-west):\n", "$$\\sum_{j = \\max(0,k-n+1)}^{\\min(0,k+1, n)} place_{(k-j),j} \\leq 1, \\qquad \\forall k \\in \\{1,..,2n-2\\} \\\\\n", "\\sum_{j = \\max(0,-k)}^{\\min(0,n-k, n)} place_{(k+j),j} \\leq 1, \\qquad \\forall k \\in \\{2-n,..,n-1\\}$$" ] }, { "cell_type": "markdown", "id": "d243b119", "metadata": {}, "source": [ "## Model implementation and results" ] }, { "cell_type": "markdown", "id": "f07bcd8c", "metadata": {}, "source": [ "The code cell below demonstrates the implementation of the above model formulation and prints the results using the Xpress Python interface.\n", "\n", "After importing the necessary modules, a 2D Numpy array of binary decision variables is created by specifying the value 'binary' for the **vartype** argument. When passing integer values for the first two arguments to [prob.addVariables()](https://www.fico.com/fico-xpress-optimization/docs/latest/solver/optimizer/python/HTML/problem.addVariables.html), the result is a NumPy array of variables.\n", "\n", "The objective and three sets of constraints are then created and directly added to the problem directly by passing the corresponding expression as a list comprehension. The problem is then optimized and an optimal solution is printed." ] }, { "cell_type": "code", "execution_count": null, "id": "35c881a2", "metadata": {}, "outputs": [], "source": [ "import xpress as xp\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "prob = xp.problem()\n", "\n", "# Variables: one per cell.\n", "n = 8\n", "N = range(n)\n", "place = prob.addVariables(n,n,vartype=xp.binary, name='place') # Create a 2D numpy array of (i,j) variables and link them to problem p\n", "\n", "# Objective function: number of queens\n", "prob.setObjective(xp.Sum(place), sense=xp.maximize)\n", "\n", "# Constraints 1: at most one queen in each row\n", "prob.addConstraint(xp.Sum(place[i,j] for j in N) <= 1 for i in N)\n", "\n", "# Constraints 2: at most one queen in each column\n", "prob.addConstraint(xp.Sum(place[i,j] for i in N) <= 1 for j in N)\n", "\n", "# Constraints 3: at most one queen on every diagonal (north-east and north-west)\n", "diagonal1 = [xp.Sum(place[k-j, j] for j in range(max(0, k-n+1), min(k+1, n))) <= 1\n", " for k in range(1, 2*n-2)]\n", "diagonal2 = [xp.Sum(place[k+j, j] for j in range(max(0, -k), min(n-k, n))) <= 1\n", " for k in range(2-n, n-1)]\n", "prob.addConstraint(diagonal1, diagonal2)\n", "\n", "prob.optimize()\n", "\n", "print(f'Here is a solution with {prob.attributes.objval} queens:')\n", "xsol = prob.getSolution(place)\n", "for i in N:\n", " for j in N:\n", " if xsol[i,j] > 0.5:\n", " print(f'\\nQueen placed in row {i+1}, column {j+1}.', end=' ')" ] }, { "cell_type": "markdown", "id": "c5a608c8", "metadata": {}, "source": [ "Now we use the *matplotlib* package to visualize the solution in an $n\\times n$ grid." ] }, { "cell_type": "code", "execution_count": null, "id": "062dad09", "metadata": {}, "outputs": [], "source": [ "# Visualize solution\n", "fig, ax = plt.subplots()\n", "\n", "min_val, max_val, diff = 0, n, 1\n", "\n", "N_points = (max_val - min_val) / diff\n", "ind_array = np.arange(min_val, max_val, diff)\n", "\n", "for i in N:\n", " for j in N:\n", " c = '\\u265B' if (xsol[i][j] > 0.5) else ' ' \n", " ax.text (i, j, c, va='center', ha='center')\n", "\n", "ax.set_aspect('equal', 'box')\n", "#set tick marks for grid\n", "ax.set_xticks(np.arange(min_val-diff/2, max_val-diff/2))\n", "ax.set_yticks(np.arange(min_val-diff/2, max_val-diff/2))\n", "ax.set_xticklabels([])\n", "ax.set_yticklabels([])\n", "ax.set_xlim(min_val-diff/2, max_val-diff/2)\n", "ax.set_ylim(min_val-diff/2, max_val-diff/2)\n", "ax.grid()\n", "plt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.9" } }, "nbformat": 4, "nbformat_minor": 5 }
| |||||||||||
© Copyright 2025 Fair Isaac Corporation. |