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.6 Reference Manual
  • Home - Combinatorics
  • Comprehensive Module List
    • Abstract Recursive Trees
    • Affine Permutations
    • Algebraic combinatorics
    • Combinatorics
    • Alternating Sign Matrices
    • Backtracking
    • Baxter permutations
    • A bijectionist’s toolkit
    • Binary Recurrence Sequences
    • Binary Trees
    • Blob Algebras
    • Cartesian Products
    • Enumerated sets of partitions, tableaux, …
    • Combinatorial Hopf algebras
    • Poirier-Reutenauer Hopf algebra of standard tableaux
    • Word Quasi-symmetric functions
    • Cluster algebras and quivers
    • ClusterSeed
    • mutation_class
    • Helper functions for mutation types of quivers
    • Quiver
    • Quiver mutation types
    • Cluster complex (or generalized dual associahedron)
    • Colored Permutations
    • Combinatorial Functions
    • Fast computation of combinatorial functions (Cython + mpz)
    • Combinations
    • Combinatorial maps
    • Integer compositions
    • Signed Compositions
    • Composition Tableaux
    • Constellations
    • Cores
    • Counting
    • Affine Crystals
    • Affine factorization crystal of type \(A\)
    • Affinization Crystals
    • Alcove paths
    • Crystals
    • Benkart-Kang-Kashiwara crystals for the general-linear Lie superalgebra
    • Catalog Of Crystals
    • Catalog Of Elementary Crystals
    • Catalog Of Crystal Models For \(B(\infty)\)
    • Catalog Of Crystal Models For Kirillov-Reshetikhin Crystals
    • An introduction to crystals
    • Direct Sum of Crystals
    • Elementary Crystals
    • Fast Rank Two Crystals
    • Fully commutative stable Grothendieck crystal
    • Crystals of Generalized Young Walls
    • Highest weight crystals
    • Induced Crystals
    • \(\mathcal{B}(\infty)\) Crystals of Tableaux in Nonexceptional Types and \(G_2\)
    • Crystals of Kac modules of the general-linear Lie superalgebra
    • Kirillov-Reshetikhin Crystals
    • Kyoto Path Model for Affine Highest Weight Crystals
    • Crystals of letters
    • Littelmann paths
    • Crystals of Modified Nakajima Monomials
    • Crystal of Bernstein-Zelevinsky Multisegments
    • Crystal Of Mirković-Vilonen (MV) Polytopes
    • \(\mathcal{B}(\infty)\) Crystal Of PBW Monomials
    • PBW Data
    • Polyhedral Realization of \(B(\infty)\)
    • Spin Crystals
    • Star-Crystal Structure On \(B(\infty)\)
    • Tensor Products of Crystals
    • Tensor Products of Crystal Elements
    • Cyclic sieving phenomenon
    • De Bruijn sequences
    • Degree sequences
    • Derangements
    • Descent Algebras
    • Combinatorial designs and incidence structures
    • Balanced Incomplete Block Designs (BIBD)
    • Resolvable Balanced Incomplete Block Design (RBIBD)
    • Group-Divisible Designs (GDD)
    • Block designs
    • Covering Arrays (CA)
    • Covering designs: coverings of \(t\)-element subsets of a \(v\)-set by \(k\)-sets
    • Database of small combinatorial designs
    • Catalog of designs
    • Cython functions for combinatorial designs
    • Difference families
    • Difference Matrices
    • Evenly distributed sets in finite fields
    • External Representations of Block Designs
    • Database of generalised quadrangles with spread
    • 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)
    • Steiner Quadruple Systems
    • Hypergraph isomorphic copy search
    • Two-graphs
    • Combinatorial diagrams
    • Diagram and Partition Algebras
    • Exact Cover Problem via Dancing Links
    • Dyck Words
    • Substitutions over unit cube faces (Rauzy fractals)
    • Enumerated sets and combinatorial objects
    • Tools for enumeration modulo the action of a permutation group
    • Compute Bell and Uppuluri-Carpenter numbers
    • Families
    • Brent Yorgey’s fast algorithm for integer vector (multiset) partitions.
    • Fully commutative elements of Coxeter groups
    • Finite state machines, automata, transducers
    • Common Automata and Transducers (Finite State Machines Generators)
    • Free Quasi-symmetric functions
    • Free modules
    • Free Dendriform Algebras
    • Free Pre-Lie Algebras
    • Fully packed loops
    • Gelfand-Tsetlin Patterns
    • Paths in Directed Acyclic Graphs
    • Gray codes
    • Growth diagrams and dual graded graphs
    • Grossman-Larson Hopf Algebras
    • Hall Polynomials
    • The Hillman-Grassl correspondence
    • Enumerated set of lists of integers with constraints: base classes
    • Enumerated set of lists of integers with constraints: front-end
    • Enumerated set of lists of integers with constraints, in inverse lexicographic order
    • Counting, generating, and manipulating nonnegative integer matrices
    • (Non-negative) Integer vectors
    • Weighted Integer Vectors
    • Integer vectors modulo the action of a permutation group
    • Tamari Interval-posets
    • Strong and weak tableaux
    • Kazhdan-Lusztig Polynomials
    • Key polynomials
    • Knutson-Tao Puzzles
    • Combinatorics on matrices
    • Dancing Links internal pyx code
    • Dancing links C++ wrapper
    • Hadamard matrices
    • Latin Squares
    • Miscellaneous
    • Ordered Multiset Partitions into Sets and the Minimaj Crystal
    • Non-commutative symmetric functions and quasi-symmetric functions
    • Common combinatorial tools
    • Generic code for bases
    • Non-Commutative Symmetric Functions
    • Quasisymmetric functions
    • Introduction to Quasisymmetric Functions
    • Symmetric functions in non-commuting variables
    • Bases for \(NCSym\)
    • Dual Symmetric Functions in Non-Commuting Variables
    • Symmetric Functions in Non-Commuting Variables
    • Necklaces
    • Non-Decreasing Parking Functions
    • \(\nu\)-Dyck Words
    • \(\nu\)-Tamari lattice
    • Ordered Rooted Trees
    • Output functions
    • Parallelogram Polyominoes
    • Parking Functions
    • Catalog of Path Tableaux
    • Dyck Paths
    • Frieze Patterns
    • Path Tableaux
    • Semistandard Tableaux
    • Plane Partitions
    • Integer partitions
    • Partition/Diagram Algebras
    • Kleshchev partitions
    • Partition Shifting Algebras
    • Partition tuples
    • Iterators over the partitions of an integer
    • Perfect matchings
    • Permutations
    • Permutations (Cython file)
    • Posets
    • Cartesian products of Posets
    • D-Complete Posets
    • Mobile posets
    • Elements of posets, lattices, semilattices, etc.
    • Forest Posets
    • Hasse diagrams of posets
    • Incidence Algebras
    • Finite lattices and semilattices
    • Linear Extensions of Posets
    • Möbius Algebras
    • Catalog of posets and lattices
    • Finite posets
    • \(q\)-Analogues
    • \(q\)-Bernoulli Numbers and Polynomials
    • Combinatorics quickref
    • Rankers
    • Recognizable Series
    • \(k\)-regular sequences
    • Restricted growth arrays
    • Ribbons
    • Ribbon Shaped Tableaux
    • Ribbon Tableaux
    • Rigged configurations
    • Abstract classes for the rigged configuration bijections
    • Bijection between rigged configurations for \(B(\infty)\) and marginally large tableaux
    • Bijection classes for type \(A_n^{(1)}\)
    • Bijection classes for type \(A_{2n}^{(2)\dagger}\)
    • Bijection classes for type \(A_{2n}^{(2)}\)
    • Bijection classes for type \(A_{2n-1}^{(2)}\).
    • Bijection classes for type \(B_n^{(1)}\)
    • Bijection classes for type \(C_n^{(1)}\)
    • Bijection classes for type \(D_n^{(1)}\)
    • Bijection classes for type \(D_{n+1}^{(2)}\)
    • Bijection classes for type \(D_4^{(3)}\)
    • Bijection between rigged configurations and KR tableaux
    • Kleber Trees
    • Kirillov-Reshetikhin Tableaux
    • Crystal of Rigged Configurations
    • Rigged Configurations of \(\mathcal{B}(\infty)\)
    • Rigged Configuration Elements
    • Rigged Configurations
    • Rigged Partitions
    • Tensor Product of Kirillov-Reshetikhin Tableaux
    • Tensor Product of Kirillov-Reshetikhin Tableaux Elements
    • Root Systems
    • 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
    • Hecke algebra representations
    • Integrable Representations of Affine Lie Algebras
    • Nonsymmetric Macdonald polynomials
    • Pieri Factors
    • Tutorial: visualizing root systems
    • Finite complex reflection groups
    • Finite real reflection groups
    • Group algebras of root lattice realizations
    • Root lattice realizations
    • Root lattices and root spaces
    • Root systems
    • Root system data for super type A
    • Root system data for type A
    • Root system data for (untwisted) type A affine
    • Root system data for type A infinity
    • Root system data for type B
    • Root system data for type BC affine
    • Root system data for (untwisted) type B affine
    • Root system data for type C
    • Root system data for (untwisted) type C affine
    • Root system data for type D
    • Root system data for (untwisted) type D affine
    • Root system data for type E
    • Root system data for (untwisted) type E affine
    • Root system data for type F
    • Root system data for (untwisted) type F affine
    • Root system data for type G
    • Root system data for (untwisted) type G affine
    • Root system data for type H
    • Root system data for type I
    • Root system data for type Q
    • Root system data for affine Cartan types
    • Root system data for dual Cartan types
    • Extended Affine Weyl Groups
    • Fundamental Group of an Extended Affine Weyl Group
    • Root system data for folded Cartan types
    • Root system data for Cartan types with marked nodes
    • Root system data for reducible Cartan types
    • Root system data for relabelled Cartan types
    • Weight lattice realizations
    • Weight lattices and weight spaces
    • Weyl Character Rings
    • Weyl Groups
    • Rooted (Unordered) Trees
    • Robinson-Schensted-Knuth correspondence
    • Schubert Polynomials
    • Set Partitions
    • Fast set partition iterators
    • Ordered Set Partitions
    • Symmetric Functions
    • Characters of the symmetric group as bases of the symmetric functions
    • Classical symmetric functions
    • Generic dual bases symmetric functions
    • Elementary symmetric functions
    • Hall-Littlewood Polynomials
    • Hecke Character Basis
    • Homogeneous symmetric functions
    • Jack Symmetric Functions
    • Quotient of symmetric function space by ideal generated by Hall-Littlewood symmetric functions
    • Kostka-Foulkes Polynomials
    • LLT symmetric functions
    • Macdonald Polynomials
    • Monomial symmetric functions
    • Multiplicative symmetric functions
    • \(k\)-Schur Functions
    • Non-symmetric Macdonald Polynomials
    • Orthogonal Symmetric Functions
    • Symmetric functions defined by orthogonality and triangularity
    • Power sum symmetric functions
    • Schur symmetric functions
    • Symplectic Symmetric Functions
    • Symmetric functions, with their multiple realizations
    • Symmetric Functions
    • Witt symmetric functions
    • Shard intersection order
    • Shifted primed tableaux
    • Shuffle product of iterables
    • Sidon sets and their generalizations, Sidon \(g\)-sets
    • Similarity class types of matrices with entries in a finite field
    • sine-Gordon Y-system plotter
    • Six Vertex Model
    • Skew Partitions
    • Skew Tableaux
    • Functions that compute some of the sequences in Sloane’s tables
    • Combinatorial species
    • Characteristic Species
    • Composition species
    • Cycle Species
    • Empty Species
    • Functorial composition species
    • Generating Series
    • Examples of Combinatorial Species
    • Linear-order Species
    • Miscellaneous Functions
    • Partition Species
    • Permutation species
    • Product species
    • Recursive Species
    • Set Species
    • Combinatorial Species
    • Species structures
    • Subset Species
    • Sum species
    • Specht Modules
    • Subsets
    • Subsets satisfying a hereditary property
    • Subsets whose elements satisfy a predicate pairwise
    • Subwords
    • Subword complex
    • Super Tableaux
    • Super Partitions
    • Symmetric Group Algebra
    • Representations of the Symmetric Group
    • T-sequences
    • Tableaux
    • Residue sequences of tableaux
    • TableauTuples
    • Generalized Tamari lattices
    • Tiling Solver
    • Transitive ideal closure tool
    • Combinatorial triangles for posets and fans
    • Tuples
    • Introduction to combinatorics in Sage
    • Vector Partitions
    • Abstract word (finite or infinite)
    • Combinatorics on words
    • Alphabet
    • Finite word
    • Infinite word
    • Lyndon words
    • Word morphisms/substitutions
    • Word paths
    • Shuffle product of words
    • Suffix Tries and Suffix Trees
    • Word classes
    • Fast word datatype using an array of unsigned char
    • Datatypes for finite words
    • Common words
    • Datatypes for words defined by iterators and callables
    • User-customizable options for words
    • Set of words
    • Yang-Baxter Graphs
    • C-Finite Sequences
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
Dyck Words
Previous
Diagram and Partition Algebras
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()