Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
Combinatorics
Light Logo Dark Logo
Version 10.7 Reference Manual
  • Home - Combinatorics
  • Comprehensive module list
    • A bijectionist’s toolkit
    • Abstract recursive trees
    • Affine permutations
    • Algebraic combinatorics
    • Alternating sign matrices
    • Backtracking
    • Baxter permutations
    • Bell and Uppuluri-Carpenter numbers
    • Binary recurrence sequences
    • Binary trees
    • Blob algebras
    • Boundedness of \(k\)-Regular Sequences
    • Brent Yorgey’s fast algorithm for integer vector (multiset) partitions
    • Cartesian products
    • Cluster complex (or generalized dual associahedron)
    • Colored permutations
    • Combinations
    • Combinatorial diagrams
    • Combinatorial functions
    • Combinatorial maps
    • Combinatorial triangles for posets and fans
    • Combinatorics
    • Introduction to combinatorics in Sage
    • Combinatorics quickref
    • Common automata and transducers (finite state machines generators)
    • Composition tableaux
    • Constellations
    • Cores
    • Counting
    • Counting, generating, and manipulating nonnegative integer matrices
    • Cyclic sieving phenomenon
    • De Bruijn sequences
    • Decorated permutations
    • Degree sequences
    • Derangements
    • Descent algebras
    • Diagram and partition algebras
    • Dyck words
    • Enumerated sets
    • Exact cover problem via dancing links
    • Families
    • Fast computation of combinatorial functions (Cython + mpz)
    • Fast set partition iterators
    • Finite state machines, automata, transducers
    • Free dendriform algebras
    • Free modules
    • Free pre-Lie algebras
    • Free quasi-symmetric functions
    • Fully commutative elements of Coxeter groups
    • Fully packed loops
    • Functions that compute some of the sequences in Sloane’s tables
    • Gelfand-Tsetlin patterns
    • Generalized Tamari lattices
    • Gray codes
    • Grossman-Larson Hopf algebras
    • Growth diagrams and dual graded graphs
    • Hall polynomials
    • Integer compositions
    • Integer partitions
    • Integer vectors modulo the action of a permutation group
    • Iterators over the partitions of an integer
    • Kazhdan-Lusztig polynomials
    • Key polynomials
    • Kleshchev partitions
    • Knutson-Tao puzzles
    • Littlewood-Richardson tableaux
    • Miscellaneous
    • Necklaces
    • Non-decreasing parking functions
    • Nonnegative integer vectors
    • Ordered multiset partitions into sets and the minimaj crystal
    • Ordered rooted trees
    • Ordered set partitions
    • Output functions
    • Parallelogram polyominoes
    • Parking functions
    • Partition shifting algebras
    • Partition tuples
    • Partition/diagram algebras
    • Partitions, tableaux, and others
    • Paths in directed acyclic graphs
    • Perfect matchings
    • Permutations
    • Permutations (Cython file)
    • Plane partitions
    • Rankers
    • Recognizable series
    • Representations of the symmetric group
    • Residue sequences of tableaux
    • Restricted growth arrays
    • Ribbon shaped tableaux
    • Ribbon tableaux
    • Ribbons
    • Robinson-Schensted-Knuth correspondence
    • Rooted (unordered) trees
    • Schubert polynomials
    • Set partitions
    • Shard intersection order
    • Shifted primed tableaux
    • Shuffle product of iterables
    • Sidon sets and their generalizations, Sidon \(g\)-sets
    • Signed compositions
    • Similarity class types of matrices with entries in a finite field
    • Six vertex model
    • Skew partitions
    • Skew tableaux
    • Specht modules
    • Steinhaus-Johnson-Trotter algorithm
    • Strong and weak tableaux
    • Subsets
    • Subsets satisfying a hereditary property
    • Subsets whose elements satisfy a predicate pairwise
    • Substitutions over unit cube faces (Rauzy fractals)
    • Subword complex
    • Subword complex: auxiliary Cython functions
    • Subwords
    • Super partitions
    • Super tableaux
    • Symmetric group algebra
    • T-sequences
    • TableauTuples
    • Tableaux
    • Tamari Interval-posets
    • The Hillman-Grassl correspondence
    • Tiling solver
    • Tools for enumeration modulo the action of a permutation group
    • Transitive ideal closure tool
    • Tuples
    • Vector partitions
    • Weighted integer vectors
    • Yang-Baxter Graphs
    • \(\nu\)-Dyck words
    • \(\nu\)-Tamari lattice
    • \(k\)-regular sequences
    • \(q\)-Bernoulli numbers and polynomials
    • \(q\)-analogues
    • sine-Gordon Y-system plotter
    • Combinatorial Hopf algebras
    • Poirier-Reutenauer Hopf algebra of standard tableaux
    • Word quasi-symmetric functions
    • Cluster algebras and quivers
    • Cluster seeds
    • Helper functions for mutation types of quivers
    • Interactive display of quivers
    • Quiver
    • Quiver mutation types
    • mutation_class
    • Affine crystals
    • Affine factorization crystal of type \(A\)
    • Affinization crystals
    • Alcove paths
    • An introduction to crystals
    • Benkart-Kang-Kashiwara crystals for the general-linear Lie superalgebra
    • Catalog of crystal models For \(B(\infty)\)
    • Catalog of crystal models for Kirillov-Reshetikhin crystals
    • Catalog of crystals
    • Catalog of elementary crystals
    • Crystal of Bernstein-Zelevinsky multisegments
    • Crystal of Mirković-Vilonen polytopes
    • Crystals
    • Crystals of Kac modules of the general-linear Lie superalgebra
    • Crystals of generalized Young walls
    • Crystals of letters
    • Crystals of modified Nakajima monomials
    • Direct sum of crystals
    • Elementary crystals
    • Fast rank two crystals
    • Fully commutative stable Grothendieck crystal
    • Highest weight crystals
    • Induced crystals
    • Kirillov-Reshetikhin crystals
    • Kyoto path model for affine highest weight crystals
    • Littelmann paths
    • PBW data
    • Polyhedral realization of \(B(\infty)\)
    • Spin crystals
    • Star-crystal structure on \(B(\infty)\)
    • Subcrystals
    • Tensor products of crystal elements
    • Tensor products of crystals
    • Virtual crystals
    • \(\mathcal{B}(\infty)\) crystal of PBW monomials
    • \(\mathcal{B}(\infty)\) crystals of tableaux in nonexceptional types and \(G_2\)
    • Balanced incomplete block designs (BIBD)
    • Block designs
    • Bounds on the number of mutually orthogonal Latin squares
    • Catalog of designs
    • Combinatorial designs and incidence structures
    • Covering arrays
    • Covering designs: coverings of \(t\)-element subsets of a \(v\)-set by \(k\)-sets
    • Cython functions for combinatorial designs
    • Database of generalised quadrangles with spread
    • Database of small combinatorial designs
    • Difference families
    • Difference matrices
    • Evenly distributed sets in finite fields
    • External representations of block designs
    • Group-divisible designs (GDD)
    • Hypergraph isomorphic copy search
    • Incidence structures (i.e. hypergraphs, i.e. set systems)
    • Mutually orthogonal Latin squares (MOLS)
    • Orthogonal arrays (OA)
    • Orthogonal arrays (build recursive constructions)
    • Orthogonal arrays (find recursive constructions)
    • Resolvable balanced incomplete block design (RBIBD)
    • Steiner quadruple systems
    • Two-graphs
    • Enumerated set of lists of integers with constraints, in inverse lexicographic order
    • Enumerated set of lists of integers with constraints: base classes
    • Enumerated set of lists of integers with constraints: front-end
    • Lists of nonnegative integers with constraints.
    • Combinatorics on matrices
    • Dancing Links internal pyx code
    • Dancing links C++ wrapper
    • Hadamard matrices
    • Latin squares
    • Common combinatorial tools
    • Generic code for bases
    • Introduction to quasisymmetric functions
    • Noncommutative symmetric functions
    • Noncommutative symmetric functions and quasi-symmetric functions
    • Quasisymmetric functions
    • Bases for NCSym
    • Dual symmetric functions in non-commuting variables
    • Symmetric functions in non-commuting variables
    • Symmetric functions in non-commuting variables
    • Catalog of path tableaux
    • Dyck paths
    • Frieze patterns
    • Path tableaux
    • Path tableaux
    • Semistandard tableaux
    • Bubble and Shuffle lattices
    • Cartesian products of posets
    • Catalog of posets and lattices
    • D-complete posets
    • Elements of posets, lattices, semilattices, etc.
    • Fast linear extension iterator
    • Finite lattices and semilattices
    • Finite posets
    • Forest posets
    • Hasse diagrams of posets
    • Hochschild lattices
    • Incidence algebras
    • Linear extensions of posets
    • Mobile posets
    • Möbius algebras
    • Posets
    • Some fast computations for finite posets
    • Some fast computations for finite posets using FLINT matrices
    • Abstract classes for the rigged configuration bijections
    • Bijection between rigged configurations and KR tableaux
    • Bijection between rigged configurations for \(B(\infty)\) and marginally large tableaux
    • Bijection classes for type \(A_n^{(1)}\)
    • Bijection classes for type \(A_{2n-1}^{(2)}\)
    • Bijection classes for type \(A_{2n}^{(2)\dagger}\)
    • Bijection classes for type \(A_{2n}^{(2)}\)
    • Bijection classes for type \(B_n^{(1)}\)
    • Bijection classes for type \(C_n^{(1)}\)
    • Bijection classes for type \(D_4^{(3)}\)
    • Bijection classes for type \(D_n^{(1)}\)
    • Bijection classes for type \(D_{n+1}^{(2)}\)
    • Bijection classes for type \(E_{6,7}^{(1)}\)
    • Crystal of rigged configurations
    • Kirillov-Reshetikhin tableaux
    • Kleber trees
    • Rigged configuration elements
    • Rigged configurations
    • Rigged configurations
    • Rigged configurations of \(\mathcal{B}(\infty)\)
    • Rigged partitions
    • Tensor product of Kirillov-Reshetikhin tableaux
    • Tensor product of Kirillov-Reshetikhin tableaux elements
    • Ambient lattices and ambient spaces
    • Associahedron
    • Braid move calculator
    • Braid orbit
    • Branching rules
    • Cartan matrices
    • Cartan types
    • Coxeter groups
    • Coxeter matrices
    • Coxeter types
    • Dynkin diagrams
    • Extended affine Weyl groups
    • Finite complex reflection groups
    • Finite real reflection groups
    • Fundamental group of an extended affine Weyl group
    • Group algebras of root lattice realizations
    • Hecke algebra representations
    • Integrable representations of affine Lie algebras
    • Nonsymmetric Macdonald polynomials
    • Pieri factors
    • Reflection group elements
    • Reflection groups: auxiliary Cython functions
    • Root lattice realizations
    • Root lattices and root spaces
    • Root system data for (untwisted) type A affine
    • Root system data for (untwisted) type B affine
    • Root system data for (untwisted) type C affine
    • Root system data for (untwisted) type D affine
    • Root system data for (untwisted) type E affine
    • Root system data for (untwisted) type F affine
    • Root system data for (untwisted) type G affine
    • Root system data for Cartan types with marked nodes
    • Root system data for affine Cartan types
    • Root system data for dual Cartan types
    • Root system data for folded Cartan types
    • Root system data for reducible Cartan types
    • Root system data for relabelled Cartan types
    • Root system data for super type A
    • Root system data for type A
    • Root system data for type A infinity
    • Root system data for type B
    • Root system data for type BC affine
    • Root system data for type C
    • Root system data for type D
    • Root system data for type E
    • Root system data for type F
    • Root system data for type G
    • Root system data for type H
    • Root system data for type I
    • Root system data for type Q
    • Root systems
    • Root systems
    • Tutorial: visualizing root systems
    • Weight lattice realizations
    • Weight lattices and weight spaces
    • Weyl character rings
    • Weyl groups
    • Abreu-Nigro symmetric functions
    • Characters of the symmetric group as bases of the symmetric functions
    • Classical symmetric functions
    • Elementary symmetric functions
    • Generic dual bases symmetric functions
    • Hall-Littlewood polynomials
    • Hecke character basis
    • Homogeneous symmetric functions
    • Jack symmetric functions
    • Kostka-Foulkes polynomials
    • LLT symmetric functions
    • Macdonald polynomials
    • Monomial symmetric functions
    • Multiplicative symmetric functions
    • Non-symmetric Macdonald polynomials
    • Orthogonal symmetric functions
    • Power sum symmetric functions
    • Quotient of symmetric function space by ideal generated by Hall-Littlewood symmetric functions
    • Schur symmetric functions
    • Symmetric functions
    • Symmetric functions
    • Symmetric functions defined by orthogonality and triangularity
    • Symmetric functions, with their multiple realizations
    • Symplectic symmetric functions
    • Witt symmetric functions
    • \(k\)-Schur functions
    • Characteristic species
    • Combinatorial species
    • Combinatorial species
    • Composition species
    • Cycle species
    • Empty species
    • Examples of combinatorial species
    • Functorial composition species
    • Generating series
    • Linear-order species
    • Miscellaneous functions
    • Partition species
    • Permutation species
    • Product species
    • Recursive species
    • Set species
    • Species structures
    • Subset species
    • Sum species
    • Abstract word (finite or infinite)
    • Alphabet
    • Combinatorics on words
    • Common words
    • Datatypes for finite words
    • Datatypes for words defined by iterators and callables
    • Fast word datatype using an array of unsigned char
    • Finite word
    • Infinite word
    • Lyndon words
    • Morphic words
    • Set of words
    • Shuffle product of words
    • Suffix tries and suffix trees
    • User-customizable options for words
    • Word classes
    • Word morphisms/substitutions
    • Word paths
    • C-finite sequences
    • Lazy Combinatorial Species
Back to top
View this page
Edit this page

Exact cover problem via dancing links¶

sage.combinat.dlx.AllExactCovers(M)[source]¶

Use A. Ajanki’s DLXMatrix class to solve the exact cover problem on the matrix M (treated as a dense binary matrix).

EXAMPLES:

sage: # needs sage.modules
sage: M = Matrix([[1,1,0],[1,0,1],[0,1,1]])  # no exact covers
sage: for cover in AllExactCovers(M):
....:     print(cover)
sage: M = Matrix([[1,1,0],[1,0,1],[0,0,1],[0,1,0]]) # two exact covers
sage: for cover in AllExactCovers(M):
....:     print(cover)
[(1, 1, 0), (0, 0, 1)]
[(1, 0, 1), (0, 1, 0)]
>>> from sage.all import *
>>> # needs sage.modules
>>> M = Matrix([[Integer(1),Integer(1),Integer(0)],[Integer(1),Integer(0),Integer(1)],[Integer(0),Integer(1),Integer(1)]])  # no exact covers
>>> for cover in AllExactCovers(M):
...     print(cover)
>>> M = Matrix([[Integer(1),Integer(1),Integer(0)],[Integer(1),Integer(0),Integer(1)],[Integer(0),Integer(0),Integer(1)],[Integer(0),Integer(1),Integer(0)]]) # two exact covers
>>> for cover in AllExactCovers(M):
...     print(cover)
[(1, 1, 0), (0, 0, 1)]
[(1, 0, 1), (0, 1, 0)]
class sage.combinat.dlx.DLXMatrix(ones, initialsolution=None)[source]¶

Bases: object

Solve the Exact Cover problem by using the Dancing Links algorithm described by Knuth.

Consider a matrix M with entries of 0 and 1, and compute a subset of the rows of this matrix which sum to the vector of all 1s.

The dancing links algorithm works particularly well for sparse matrices, so the input is a list of lists of the form: (note the 1-index!):

[
 [1, [i_11,i_12,...,i_1r]]
 ...
 [m,[i_m1,i_m2,...,i_ms]]
]

where M[j][i_jk] = 1.

The first example below corresponds to the matrix:

1110
1010
0100
0001

which is exactly covered by:

1110
0001

and

1010
0100
0001

EXAMPLES:

sage: from sage.combinat.dlx import *
sage: ones = [[1,[1,2,3]]]
sage: ones+= [[2,[1,3]]]
sage: ones+= [[3,[2]]]
sage: ones+= [[4,[4]]]
sage: DLXM = DLXMatrix(ones,[4])
sage: for C in DLXM:
....:      print(C)
[4, 1]
[4, 2, 3]
>>> from sage.all import *
>>> from sage.combinat.dlx import *
>>> ones = [[Integer(1),[Integer(1),Integer(2),Integer(3)]]]
>>> ones+= [[Integer(2),[Integer(1),Integer(3)]]]
>>> ones+= [[Integer(3),[Integer(2)]]]
>>> ones+= [[Integer(4),[Integer(4)]]]
>>> DLXM = DLXMatrix(ones,[Integer(4)])
>>> for C in DLXM:
...      print(C)
[4, 1]
[4, 2, 3]

Note

The 0 entry is reserved internally for headers in the sparse representation, so rows and columns begin their indexing with 1. Apologies for any heartache this causes. Blame the original author, or fix it yourself.

next()[source]¶

Search for the first solution we can find, and return it.

Knuth describes the Dancing Links algorithm recursively, though actually implementing it as a recursive algorithm is permissible only for highly restricted problems. (for example, the original author implemented this for Sudoku, and it works beautifully there)

What follows is an iterative description of DLX:

stack <- [(NULL)]
level <- 0
while level >= 0:
    cur <- stack[level]
    if cur = NULL:
        if R[h] = h:
            level <- level - 1
            yield solution
        else:
            cover(best_column)
            stack[level] = best_column
    else if D[cur] != C[cur]:
        if cur != C[cur]:
            delete solution[level]
            for j in L[cur], L[L[cur]], ... , while j != cur:
                uncover(C[j])
        cur <- D[cur]
        solution[level] <- cur
        stack[level] <- cur
        for j in R[cur], R[R[cur]], ... , while j != cur:
            cover(C[j])
        level <- level + 1
        stack[level] <- (NULL)
    else:
        if C[cur] != cur:
            delete solution[level]
            for j in L[cur], L[L[cur]], ... , while j != cur:
                uncover(C[j])
        uncover(cur)
        level <- level - 1
sage.combinat.dlx.OneExactCover(M)[source]¶

Use A. Ajanki’s DLXMatrix class to solve the exact cover problem on the matrix M (treated as a dense binary matrix).

EXAMPLES:

sage: M = Matrix([[1,1,0],[1,0,1],[0,1,1]])  # no exact covers                  # needs sage.modules
sage: OneExactCover(M)                                                          # needs sage.modules

sage: M = Matrix([[1,1,0],[1,0,1],[0,0,1],[0,1,0]])  # two exact covers         # needs sage.modules
sage: OneExactCover(M)                                                          # needs sage.modules
[(1, 1, 0), (0, 0, 1)]
>>> from sage.all import *
>>> M = Matrix([[Integer(1),Integer(1),Integer(0)],[Integer(1),Integer(0),Integer(1)],[Integer(0),Integer(1),Integer(1)]])  # no exact covers                  # needs sage.modules
>>> OneExactCover(M)                                                          # needs sage.modules

>>> M = Matrix([[Integer(1),Integer(1),Integer(0)],[Integer(1),Integer(0),Integer(1)],[Integer(0),Integer(0),Integer(1)],[Integer(0),Integer(1),Integer(0)]])  # two exact covers         # needs sage.modules
>>> OneExactCover(M)                                                          # needs sage.modules
[(1, 1, 0), (0, 0, 1)]
Next
Families
Previous
Enumerated sets
Copyright © 2005--2025, The Sage Development Team
Made with Sphinx and @pradyunsg's Furo
On this page
  • Exact cover problem via dancing links
    • AllExactCovers()
    • DLXMatrix
      • next()
    • OneExactCover()