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
Beispiel #2
0
    def __call__(self, sudoku):
        board, metadata = SudokuSolver.parse(sudoku)
        result = DLX.solve(board)
        if result is None:
            return None

        # Draw back the solution.
        solution = np.zeros((9, 9))
        for row in result:
            cell = metadata[row]
            solution[cell.row, cell.col] = cell.val
        return solution