File indexing completed on 2024-04-28 04:04:44
0001 /**************************************************************************** 0002 * Copyright 2015 Ian Wadham <iandw.au@gmail.com> * 0003 * * 0004 * This program is free software; you can redistribute it and/or * 0005 * modify it under the terms of the GNU General Public License as * 0006 * published by the Free Software Foundation; either version 2 of * 0007 * the License, or (at your option) any later version. * 0008 * * 0009 * This program is distributed in the hope that it will be useful, * 0010 * but WITHOUT ANY WARRANTY; without even the implied warranty of * 0011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * 0012 * GNU General Public License for more details. * 0013 * * 0014 * You should have received a copy of the GNU General Public License * 0015 * along with this program. If not, see <http://www.gnu.org/licenses/>. * 0016 ****************************************************************************/ 0017 0018 #ifndef DLXSOLVER_H 0019 #define DLXSOLVER_H 0020 0021 #include <QList> 0022 #include <QObject> 0023 0024 #include "globals.h" 0025 #include "skgraph.h" 0026 0027 struct DLXNode // Represents a 1 in a sparse matrix 0028 // containing only ones and zeroes. 0029 { 0030 DLXNode * left; // Link to next node left. 0031 DLXNode * right; // Link to next node right. 0032 DLXNode * above; // Link to next node above. 0033 DLXNode * below; // Link to next node below. 0034 0035 DLXNode * columnHeader; // Link to top of column. 0036 int value; // In col header: count of ones in col. 0037 // In node: row-number of node. 0038 }; 0039 0040 /** 0041 * @class DLXSolver dlxsolver.h 0042 * @short Provides a solver, based on the DLX algorithm, for Sudoku variants. 0043 * 0044 * This solver can handle all variants of Sudoku puzzles supported by KSudoku, 0045 * including classical 9x9 Sudokus, 2-D variants, 3-D variants, Killer Sudoku 0046 * and MathDoku (aka KenKen TM). 0047 * 0048 * Killer and MathDoku puzzles have cages in which all the numbers must satisfy 0049 * an arithmetic constraint, as well as satisfying the usual Sudoku constraints 0050 * (using all numbers exactly once each in a column, row or group). Killer 0051 * Sudokus have 9x9 cells and nine 3x3 boxes, but there are no clues and each 0052 * cage must add up to a prescribed total. MathDokus can have N x N cells, for 0053 * N >= 3, but no boxes. Each cage has an operator (+, -, multiply or divide) 0054 * which must be used to reach the required value. In Killers and Mathdokus, a 0055 * cage with just one cell is effectively a clue. 0056 * 0057 * The DLX algorithm (aka Dancing Links) is due to Donald Knuth. 0058 */ 0059 class DLXSolver : public QObject 0060 { 0061 Q_OBJECT 0062 public: 0063 explicit DLXSolver (QObject * parent); 0064 ~DLXSolver() override; 0065 0066 /** 0067 * Takes any of the various kinds of 2-D Sudoku or 3-D Roxdoku puzzle 0068 * supported by the KSudoku application program and converts it into a 0069 * sparse matrix of constraints and possible solution values for each 0070 * vacant cell. It then calls the solveDLX method to solve the puzzle, 0071 * using Donald Knuth's Dancing Links (DLX) algorithm. The algorithm can 0072 * find zero, one or any number of solutions, each of which can converted 0073 * back into a KSudoku grid containing a solution. 0074 * 0075 * Each column in the DLX matrix represents a constraint that must be 0076 * satisfied. In a Classic 9x9 Sudoku, there are 81 constraints to say that 0077 * each cell must be filled in exactly once. Then there are 9x9 constraints 0078 * to say that each of the 9 Sudoku columns must contain the numbers 1 to 9 0079 * exactly once. Similarly for the 9 Sudoku rows and the 9 3x3 boxes. In 0080 * total, there are 81 + 9x9 + 9x9 + 9x9 = 324 constraints and so there are 0081 * 324 columns in the DLX matrix. 0082 * 0083 * Each row in the DLX matrix represents a position in the Sudoku grid and 0084 * a value (1 to 9) that might go there. If it does, it will satisfy 4 of 0085 * the constraints: filling in a cell and putting that value in a column, a 0086 * row and a 3x3 box. That possibility is represented by a 1 in that row in 0087 * each of the corresponding constraint columns. Thus there are 4 ones in 0088 * each row of the 9x9 Sudoku's DLX matrix and in total there 9x81 = 729 0089 * rows, representing a possible 1 to 9 in each of 81 cells. 0090 * 0091 * A solution to the 9x9 Sudoku will consist of a set of 81 rows such that 0092 * each column contains a single 1. That means that each constraint is 0093 * satisfied exactly once, as required by the rules of Sudoku. Each of the 0094 * successful 81 rows will still contain its original four 1's, representing 0095 * the constraints the corresponding Sudoku cell and value satisfies. 0096 * 0097 * Applying clues reduces the rows to be found by whatever the number of 0098 * clues is --- and it also reduces the size of the DLX matrix considerably. 0099 * For example, for a 9x9 Classic Sudoku, the size can reduce from 729x324 0100 * to 224x228 or even less. Furthermore, many of the remaining columns 0101 * contain a single 1 already, so the solution becomes quite fast. 0102 * 0103 * KSudoku can handle other sizes and shapes of Sudoku puzzle, including the 0104 * 3-D Roxdoku puzzles. For example, an XSudoku is like a Classic 9x9 puzzle 0105 * except that the two diagonals must each contain the numbers 1 to 9 once 0106 * and once only. In DLX, this can be represented by 18 additional columns 0107 * to represent the constraints on the diagonals. Also a group of 9 cells 0108 * might not have a simple row, column or 3x3 box shape, as in a jigsaw 0109 * type of Sudoku or a 3-D Roxdoku, and a Samurai Sudoku has five 9x9 0110 * grids overlapping inside a 21x21 array of cells, some of which must NOT 0111 * be used. All this is represented by lists of cells in the SKGraph object, 0112 * known as "cliques" or "groups". So, in the more general case, each group 0113 * of 9 cells will have its own 9 constraints or DLX matrix columns. 0114 * 0115 * @param graph An SKGraph object representing the size, geometric 0116 * layout and rules of the particular kind of puzzle. 0117 * @param boardValues A vector containing clue values, vacant cells and 0118 * unused values for the puzzle and its layout. 0119 * @param solutionLimit A limit to the number of solutions to be delivered 0120 * where 0 = no limit, 1 gets the first solution only 0121 * and 2 is used to test if there is > 1 solution. 0122 * 0123 * @return The number of solutions found (0 to solutionLimit). 0124 */ 0125 int solveSudoku (SKGraph * graph, const BoardContents & boardValues, 0126 int solutionLimit = 2); 0127 0128 /** 0129 * Takes a Mathdoku or Killer Sudoku puzzle and converts it into a sparse 0130 * matrix of constraints and possible solution values for each cage. The 0131 * constraints are that each cage must be filled in and that each column 0132 * and row of the puzzle solution must follow Sudoku rules (blocks too, in 0133 * Killer Sudoku). The possible solutions are represented by one DLX row per 0134 * possible set of numbers for each cage. The solveDLX() method is then used 0135 * to test that the puzzle has one and only one solution, which consists of 0136 * a subset of the original DLX rows (i.e. one set of numbers per cage). For 0137 * more detail, see solveSudoku(). 0138 * 0139 * @param graph An SKGraph object representing the size, geometric 0140 * layout and rules of the particular kind of puzzle, 0141 * as well as its cage layouts, values and operators. 0142 * @param solutionMoves A pointer that returns an ordered list of cells 0143 * found by the solver when it reaches a solution. 0144 * @param possibilities A pointer to a list of possible values for all the 0145 * cells in all the cages. 0146 * @param possibilitiesIndex 0147 * An index into the possibilities list, with one 0148 * index-entry per cage, plus an end-of-list index. 0149 * @param solutionLimit A limit to the number of solutions to be delivered 0150 * where 0 = no limit, 1 gets the first solution only 0151 * and 2 is used to test if there is > 1 solution. 0152 * 0153 * @return The number of solutions found (0 to solutionLimit). 0154 */ 0155 int solveMathdoku (SKGraph * graph, QList<int> * solutionMoves, 0156 const QList<int> * possibilities, 0157 const QList<int> * possibilitiesIndex, 0158 int solutionLimit = 2); 0159 0160 /** 0161 * Copy back to the caller the last solution found by the solver. 0162 * 0163 * @param solution A BoardContents object to receive the solution. 0164 */ 0165 void retrieveSolution (BoardContents & solution); 0166 0167 // void testDLX(); // TODO - Delete this eventually. 0168 0169 private: 0170 /** 0171 * Takes a sparse matrix of ones and zeroes and solves the Exact Cover 0172 * Problem for it, using Donald Knuth's Dancing Links (DLX) algorithm. 0173 * 0174 * A solution is a subset of rows which, when combined, have a single 1 in 0175 * each column. If each DLX column represents a constraint or condition that 0176 * must be satisfied exactly once and each row represents a possible part of 0177 * the solution, then the whole matrix can represent a problem such as 0178 * Sudoku or Mathdoku and the subset of rows can represent a solution to 0179 * that Sudoku or Mathdoku. A particular matrix can have 0, 1 or any number 0180 * of Exact Cover solutions, as can the corresponding puzzle. 0181 * 0182 * See the code in file dlxsolver.cpp for a description of the algorithm. 0183 * 0184 * @param solutionLimit A limit to the number of solutions to be delivered 0185 * where 0 = no limit, 1 gets the first solution only 0186 * and 2 is used to test if there is > 1 solution. 0187 * 0188 * @return The number of solutions found (0 to solutionLimit). 0189 * Actual solutions are returned progressively a Qt 0190 * signal-slot mechanism. 0191 */ 0192 int solveDLX (int solutionLimit); 0193 0194 /** 0195 * Temporarily remove a column from the DLX matrix, along with all of the 0196 * rows that have nodes (1's) in this column. 0197 * 0198 * @param colDLX A pointer to the header of the column. 0199 */ 0200 void coverColumn (DLXNode * colDLX); 0201 0202 /** 0203 * Re-insert a column into the DLX matrix, along with all of the rows that 0204 * have nodes (1's) in this column. 0205 * 0206 * @param colDLX A pointer to the header of the column. 0207 */ 0208 void uncoverColumn (DLXNode * colDLX); 0209 0210 void recordSolution (const int solutionNum, QList<DLXNode *> & solution); 0211 0212 // Empty the DLX matrix, but do not deallocate the nodes. 0213 void clear(); 0214 0215 // Add a node (i.e. a 1) to the sparse DLX matrix. 0216 void addNode (int rowNum, int colNum); 0217 0218 // Get a node-structure, allocating or re-using as needed. 0219 DLXNode * allocNode(); 0220 0221 // Initialise a node to point to itself and contain value 0. 0222 void initNode (DLXNode * node); 0223 0224 // Circularly link a node to the end of a DLX matrix row. 0225 void addAtRight (DLXNode * node, DLXNode * start); 0226 0227 // Circularly link a node to the end of a DLX matrix column. 0228 void addBelow (DLXNode * node, DLXNode * start); 0229 0230 // Deallocate all nodes. 0231 void deleteAll(); 0232 0233 DLXNode * mCorner; 0234 QList<DLXNode *> mColumns; 0235 QList<DLXNode *> mRows; 0236 QList<DLXNode *> mNodes; 0237 int mEndColNum; 0238 int mEndRowNum; 0239 int mEndNodeNum; 0240 0241 BoardContents mBoardValues; // Holds Sudoku problem and solution. 0242 QList<int> * mSolutionMoves; // Sequence of cells used in solution. 0243 SKGraph * mGraph; 0244 const QList<int> * mPossibilities; 0245 const QList<int> * mPossibilitiesIndex; 0246 0247 // Print the current state of the Sudoku puzzle. 0248 void printSudoku(); 0249 0250 // Print DLX matrix (default is to skip printing those that are too large). 0251 void printDLX (bool forced = false); 0252 }; 0253 0254 #endif // DLXSOLVER_H