def get_exact_covers(cols, rows, num_cols=None): """ Use Algorithm X to get all solutions to the exact cover problem https://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X Args: cols (list[int]): A list of integers representing the columns to be covered rows (list[list[int]]): A list of lists of integers representing the rows num_cols (int): The total number of columns Returns: list: All exact covers """ if num_cols is None: num_cols = max(cols) + 1 ec = DLX([(c, 0 if c in cols else 1) for c in range(num_cols)]) ec.appendRows([[c] for c in cols]) ec.appendRows(rows) exact_covers = [] for s in ec.solve(): cover = [] for i in s: cover.append(ec.getRowList(i)) exact_covers.append(cover) return exact_covers
def __init__(self, squares): """Squares is a nested list representing an initial sudoku board. A 0 represents an empty square, while a nonzero digit represents a square filled with that value.""" self.dlxrows = squares self.sparseMatrix = SparseMatrix(self.dlxrows) self.dlx = DLX(self.sparseMatrix)
def main(): if (len(sys.argv) != 2): print("usage: python3 solveitup.py <problem description>") return numvars, clauses = getproblem(sys.argv[1]) grid = buildgrid(numvars, clauses) dlx = DLX(SparseMatrix(grid)) results = dlx.search() printresults(results)
X="#BB99DD", Y="#CC88CC", Z="#DD99BB") # Grid for Scott's pentomino problem: 8x8 with a 2x2 hole in the middle GRID = Grid((8, 8), holes=[(3, 3), (3, 4), (4, 3), (4, 4)]) # Generate all pentominoes that can be placed on the grid POLYMINOES = generate_all(PENTOMINOES, GRID) # convert to list of lists POLYMINOES = [polymino.aslist for polymino in POLYMINOES] # calculate labels for DLX LABELS = list(set([element for polymino in POLYMINOES for element in polymino])) LABELS = sorted(LABELS, key=sortkey) COVER = DLX(LABELS, POLYMINOES) SOLUTIONS = [] for i, SOLUTION in enumerate(COVER.generate_solutions()): print(i) SOLUTIONS.append(Grid.from_DLX(SOLUTION)) DISTINCT_SOLUTIONS = unique_grids(SOLUTIONS) solutions_svg(DISTINCT_SOLUTIONS, filename='scott_distinct_solutions1.svg', columns=13, colour=COLOURS.get) # removing X pentominoes POLYMINOES = [pol for pol in POLYMINOES if not (pol[0] == 'X' and pol[1] not in [(5, 3), (5, 2), (4, 2)])] COVER = DLX(LABELS, POLYMINOES)