dlx

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 1 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

dlx Go Reference License CI Coverage Status

dlx solves exact cover problems in Go, using Knuth's algorithm DLX.

An exact cover problem is a table of 0s and 1s. The task is to pick some of its rows so that every column has a 1 in exactly one picked row: no column is missed and no column is covered twice. Think of the columns as requirements and the rows as choices, each meeting some of the requirements.

DLX is a backtracking search. It picks a column, tries each row that covers it, removes everything that row conflicts with, and continues until all columns are covered or it hits a dead end. The removals are undone cheaply through doubly linked lists, the "dancing links" of the name. DLX is Algorithm X implemented this way, and Knuth's paper "Dancing Links" explains it in full.

What it can be used for

You turn your problem into a table, and dlx reports the sets of rows that solve it. The problem fits directly if every requirement must be met exactly once:

  • Sudoku: each cell, and each digit in each row, column and box, is a column; each possible digit placement is a row. See the sudoku solver.
  • Tiling and pentomino puzzles where every cell is filled and, for pentominoes, every piece is used: each cell and piece is a column; each placement of a piece is a row.
  • Assignment problems where every task and every slot is used exactly once: each task and slot is a column; each allowed pairing is a row.

Example programs

Each one is a small command with a README that explains how the problem maps to exact cover. If exact cover is new to you, start with the gentle introduction. It also explains slack rows, the way to say "at most once".

Puzzles
Example Problem What it teaches
sudoku Solve a Sudoku board. The standard introduction to exact cover: one move meets four requirements at once.
pentomino Tile a rectangle with the 12 pentominoes. Two kinds of column in one matrix, and counting a tiling's flips and half turns as one.
queens Place n queens so that no two attack each other. "At most once" with slack rows, and what slack rows cost the search.
langford Line up two copies of each number, with k numbers between the copies of k. Removing mirror-image solutions from the matrix itself.
cardtrick Find a strategy for a trick where the assistant picks which card to hide and how to lay out the rest, so the magician can name it. Slack rows for spare messages, counting that rules out a deck with no search, and a recipe that reaches decks the search can't.
Science and maths
Example Problem What it teaches
kochenspecker Show that Peres's 33 rays can't be painted green or red so that no two perpendicular rays are both green and every three perpendicular rays include one green. Proof by zero solutions: the search finds no answer, and that empty result is the Kochen-Specker theorem.
fullerene Find the double bonds of the C60 molecule. A scientific count: the 12500 structures found by search match a published total and a calculation that needs no search.
witt Find Steiner systems, such as 132 committees of six drawn from twelve people, where any five people share exactly one. A matrix that is the definition itself, and totals that measure symmetry, cross-checked by a division.
hat Cover a disk with copies of the hat, the shape that covers the plane only without repeating. Slack rows for the kites outside the disk, and a zero result: turned copies alone can't cover this disk of radius 6.
hamming Find perfect codes: sets of words of 0s and 1s where every word is at most one flip from exactly one chosen word. Use one to win a hat game 7 times out of 8. One row per neighbourhood, with the search's 240 codes rebuilt by Hamming's recipe.
coveringsystems Split all whole numbers into groups like "every 3rd number", so that each number is in exactly one group. A finite matrix for an infinite question, totals checked against a known sequence, and zero solutions backing a theorem.
Music
Example Problem What it teaches
twelvetone Order the twelve notes so that every interval appears exactly once. The equality trick, which makes two rows agree on a value. The totals match the published counts.
vuza Find where copies of a rhythm must enter so that every beat is struck once, and neither rhythm nor entries repeat. Filtering in the callback that receives each solution: dlx finds every list of entries, and those that repeat are dropped. The results match published counts.
bells Ring all 24 orders of four bells exactly once under the rules of change ringing. Filtering in the callback that receives each solution, for a rule no column states: the steps must form a single loop. With all four kinds of swap allowed, 10792 of 2655552 covers pass, which is the published total.
Computing and scheduling
Example Problem What it teaches
crew Choose crew pairings so that each flight is flown exactly once, at the lowest cost. Ranking by cost outside dlx, and handling rows with equal columns.
instrselect Choose machine instructions for an expression by covering its tree with tiles. Ranking by cost outside dlx, why the tiles join up with no extra rule, and when dynamic programming is the better tool.
perfecthash Find a rule that gives each of Go's 25 keywords its own box in a table of exactly 25 boxes, known as a minimal perfect hash. Two kinds of column, and why a minimal table needs no slack rows: every slot must be used.

What it doesn't do

  • There are no secondary columns: every column must be covered exactly once, so "at most once" can't be stated directly. You can get that effect by adding a row with that column alone, called a slack row, and dropping such rows from the solutions you receive. This assumes no real row consists of that column alone, since the two could not be told apart. A problem where many requirements are optional, such as scheduling with free time slots, may suit another tool better.
  • It doesn't optimize. Rows have no costs or weights, so it finds solutions but doesn't rank them.
  • It can't be cancelled or timed out. Exact cover is NP-complete, so a search can take very long, and your code only runs when a solution is found.
  • It doesn't identify rows. A solution lists each picked row's column indices, not its position, so your columns must let you tell the rows apart. The sudoku solver decodes each placement from its column indices.

Installation

go get github.com/dimchansky/dlx

Requires Go 1.19 or later. No dependencies outside the standard library.

Example

This matrix has seven columns and six rows:

0 1 2 3 4 5 6
1 0 0 1 0 0 1
1 0 0 1 0 0 0
0 0 0 1 1 0 1
0 0 1 0 1 1 0
0 1 1 0 0 1 1
0 1 0 0 0 0 1

Each AddRow call lists the columns that hold a 1 in that row:

package main

import (
	"fmt"

	"github.com/dimchansky/dlx"
)

func main() {
	m := dlx.NewMatrix(7)
	m.AddRow(0, 3, 6)
	m.AddRow(0, 3)
	m.AddRow(3, 4, 6)
	m.AddRow(2, 4, 5)
	m.AddRow(1, 2, 5, 6)
	m.AddRow(1, 6)

	m.Solve(dlx.SolutionAccepterFunc(func(exactCover [][]int) bool {
		fmt.Println("Solution found:")
		for _, row := range exactCover {
			fmt.Println(row)
		}
		return false // keep searching
	}))
}

Output:

Solution found:
[0 3]
[2 4 5]
[1 6]

This is the only solution: the second, fourth and sixth rows.

Stopping early

Return true from the accepter to stop the search. This matrix has two solutions, and the search ends after the first:

m := dlx.NewMatrix(2)
m.AddRow(0)
m.AddRow(1)
m.AddRow(0, 1)

m.Solve(dlx.SolutionAccepterFunc(func(exactCover [][]int) bool {
	fmt.Println(exactCover) // [[0] [1]]
	return true
}))

Behavior

  • Solution order is deterministic: matrices built by the same AddRow calls report the same solutions in the same order. The search branches on the leftmost column with the fewest remaining rows and tries that column's rows in AddRow order.
  • Within a solution, rows appear in the order the search selected them, not in AddRow order. Each row lists its columns in the order they were passed to AddRow.
  • The accepter owns the slices it receives: they are freshly allocated for each solution, so it can keep and modify them. AddRow doesn't keep the slice passed to it.
  • A Matrix stays valid after Solve returns, however the search ended: you can solve it again or add more rows.
  • If the accepter panics, the matrix is left in an undefined state and must be discarded.
  • A row with no columns is ignored. A row added twice counts as two rows and gives separate solutions.
  • A matrix with no columns has one solution, which is empty. A matrix with a column that no row covers has none.
  • Invalid arguments panic with a message prefixed dlx:: a negative column count, a column index that is out of range or repeated within a row, and a nil SolutionAccepter. A rejected row leaves the matrix unchanged. A nil SolutionAccepterFunc is not detected and panics with a runtime error when the first solution is reported.
  • A Matrix is not safe for concurrent use, including concurrent calls to Solve.
  • The accepter must not call AddRow or Solve on the matrix being solved.

License

Apache License 2.0

Documentation

Overview

Package dlx implements Knuth's algorithm DLX (algorithm X implemented in terms of dancing links), which solves exact cover problems.

An exact cover problem is a matrix of 0s and 1s. A solution is a subset of its rows that contains exactly one 1 in each column. Many puzzles and combinatorial problems reduce to this form: see the sudoku solver in the examples/sudoku directory.

Knuth's paper explains the algorithm: https://arxiv.org/abs/cs/0011047

Usage

Consider the exact cover problem specified by the matrix:

1	0	0	1	0	0	1
1	0	0	1	0	0	0
0	0	0	1	1	0	1
0	0	1	0	1	1	0
0	1	1	0	0	1	1
0	1	0	0	0	0	1

The following code finds all solutions to the exact cover problem:

m := dlx.NewMatrix(7)
m.AddRow(0, 3, 6)
m.AddRow(0, 3)
m.AddRow(3, 4, 6)
m.AddRow(2, 4, 5)
m.AddRow(1, 2, 5, 6)
m.AddRow(1, 6)

m.Solve(dlx.SolutionAccepterFunc(func(exactCover [][]int) bool {
	fmt.Println("Solution found:")
	for _, row := range exactCover {
		fmt.Println(row)
	}
	return false
}))

The code output:

Solution found:
[0 3]
[2 4 5]
[1 6]

Contract

Return true from the accepter to stop the search early. A Matrix stays valid after Solve returns, however the search ended, so it can be solved again and more rows can be added to it.

Invalid arguments are programmer errors and panic with a message prefixed "dlx:". This applies to a negative column count, a column index that is out of range or repeated within a row, and a nil SolutionAccepter interface value. A nil SolutionAccepterFunc is not detected: it panics with a runtime error when the first solution is reported. A rejected row leaves the matrix unchanged.

A Matrix is not safe for concurrent use, and an accepter must not call AddRow or Solve on the matrix being solved. See the Matrix and SolutionAccepter documentation for the details.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Matrix

type Matrix interface {
	// AddRow adds a row to the matrix. constraintsRow lists the zero-based
	// column indices of the row's 1s, in any order. The slice is not retained.
	//
	// A row with no indices is ignored: it could not cover anything. Rows have
	// no identity, so a row added twice is two rows and yields separate
	// solutions.
	//
	// AddRow panics if an index is outside [0, nColumns) or appears twice in
	// constraintsRow. The matrix is unchanged after such a panic.
	AddRow(constraintsRow ...int)

	// Solve searches for every subset of rows that has exactly one 1 in each
	// column, and passes each one to accepter. The search ends when accepter
	// returns true or when no solutions remain.
	//
	// A matrix with no columns has exactly one solution, which is empty. A
	// matrix with a column that no row covers has none.
	//
	// The order of the search is deterministic: matrices built by the same
	// sequence of AddRow calls report the same solutions in the same order.
	// It branches on the leftmost column with the fewest remaining rows, trying
	// that column's rows in AddRow order.
	//
	// Solve restores the matrix before returning, even after accepter stops the
	// search, so it can be called again and more rows can be added. Recursion
	// depth is bounded by the number of columns.
	//
	// Solve panics with a "dlx:" message if accepter is a nil interface value.
	// A nil SolutionAccepterFunc is not detected: it panics with a runtime error
	// when the first solution is reported, like any panicking accepter.
	Solve(accepter SolutionAccepter)
}

Matrix represents an exact cover problem: a matrix of 0s and 1s, for which Solve looks for a subset of rows with exactly one 1 in every column.

A Matrix is not safe for concurrent use, including concurrent calls to Solve.

func NewMatrix

func NewMatrix(nColumns int) Matrix

NewMatrix creates the Matrix with the given number of columns. It panics with a "dlx:" message if nColumns is negative. An extremely large nColumns fails with a runtime allocation panic instead.

Example
package main

import (
	"fmt"

	"github.com/dimchansky/dlx"
)

func main() {
	m := dlx.NewMatrix(7)
	m.AddRow(0, 3, 6)
	m.AddRow(0, 3)
	m.AddRow(3, 4, 6)
	m.AddRow(2, 4, 5)
	m.AddRow(1, 2, 5, 6)
	m.AddRow(1, 6)

	m.Solve(dlx.SolutionAccepterFunc(func(exactCover [][]int) bool {
		fmt.Println("Solution found:")
		for _, row := range exactCover {
			fmt.Println(row)
		}
		return false
	}))

}
Output:
Solution found:
[0 3]
[2 4 5]
[1 6]

type SolutionAccepter

type SolutionAccepter interface {
	// AcceptSolution receives one solution and returns true to stop the search.
	//
	// exactCover holds one element per selected row, each listing the row's
	// column indices in the order they were passed to AddRow. The rows appear
	// in the order the search selected them, not in AddRow order. Both levels
	// of the slice are freshly allocated, so it is safe to retain and modify.
	//
	// AcceptSolution must not call AddRow or Solve on the matrix being solved.
	// If it panics, the matrix is left in an undefined state and must be
	// discarded.
	AcceptSolution(exactCover [][]int) bool
}

SolutionAccepter receives the solutions of an exact cover problem.

type SolutionAccepterFunc

type SolutionAccepterFunc func([][]int) bool

The SolutionAccepterFunc type is an adapter to allow the use of ordinary functions as SolutionAccepter. If f is a function with the appropriate signature, SolutionAccepterFunc(f) is a SolutionAccepter that calls f.

func (SolutionAccepterFunc) AcceptSolution

func (f SolutionAccepterFunc) AcceptSolution(exactCover [][]int) bool

AcceptSolution calls f(exactCover) and returns its result.

Directories

Path Synopsis
examples
bells command
Command bells searches for extents of change ringing on 3 or 4 bells, and prints them to standard output.
Command bells searches for extents of change ringing on 3 or 4 bells, and prints them to standard output.
cardtrick command
Command cardtrick finds a strategy for the five-card trick of Fitch Cheney in its general form, using exact cover.
Command cardtrick finds a strategy for the five-card trick of Fitch Cheney in its general form, using exact cover.
coveringsystems command
Command coveringsystems splits the integers into remainder classes, such as the even numbers, the numbers that leave 1 when divided by 4, and the numbers that leave 3, so that every integer lands in exactly one class.
Command coveringsystems splits the integers into remainder classes, such as the even numbers, the numbers that leave 1 when divided by 4, and the numbers that leave 3, so that every integer lands in exactly one class.
crew command
Command crew reads the flights of a day and a list of candidate crew pairings with their costs from standard input.
Command crew reads the flights of a day and a list of candidate crew pairings with their costs from standard input.
fullerene command
Command fullerene finds the double bonds of a carbon molecule, by default the football-shaped C60, and prints them to standard output.
Command fullerene finds the double bonds of a carbon molecule, by default the football-shaped C60, and prints them to standard output.
hamming command
Command hamming finds perfect codes and uses one to play the seven prisoners hat game.
Command hamming finds perfect codes and uses one to play the seven prisoners hat game.
hat command
Command hat tries to cover a disk with copies of the hat, the aperiodic monotile found in 2023, and prints what it finds to standard output.
Command hat tries to cover a disk with copies of the hat, the aperiodic monotile found in 2023, and prints what it finds to standard output.
instrselect command
Command instrselect picks machine instructions for an arithmetic expression, the way the instruction selection step of a compiler does.
Command instrselect picks machine instructions for an arithmetic expression, the way the instruction selection step of a compiler does.
kochenspecker command
Command kochenspecker tries to colour a set of rays green and red under the rules of the Kochen-Specker theorem: exactly one green ray in every group of mutually perpendicular rays that fills all directions, and at most one green ray in every other perpendicular pair.
Command kochenspecker tries to colour a set of rays green and red under the rules of the Kochen-Specker theorem: exactly one green ray in every group of mutually perpendicular rays that fills all directions, and at most one green ray in every other perpendicular pair.
langford command
Command langford arranges two copies of each number from 1 to n in a row, so that the copies of a number k have exactly k numbers between them, and prints the arrangements to standard output.
Command langford arranges two copies of each number from 1 to n in a row, so that the copies of a number k have exactly k numbers between them, and prints the arrangements to standard output.
pentomino command
Command pentomino tiles a rectangle of 60 cells with the 12 pentominoes, each used exactly once, and prints the tilings to standard output.
Command pentomino tiles a rectangle of 60 cells with the 12 pentominoes, each used exactly once, and prints the tilings to standard output.
perfecthash command
Command perfecthash builds a minimal perfect hash for a list of lowercase words: a table with exactly one slot per word, and a small sum that sends each word to its own slot.
Command perfecthash builds a minimal perfect hash for a list of lowercase words: a table with exactly one slot per word, and a small sum that sends each word to its own slot.
queens command
Command queens places n queens on an n by n chessboard so that no two attack each other, and prints the solutions to standard output.
Command queens places n queens on an n by n chessboard so that no two attack each other, and prints the solutions to standard output.
sudoku command
Command sudoku solves the Sudoku board read from standard input and prints its solutions to standard output.
Command sudoku solves the Sudoku board read from standard input and prints its solutions to standard output.
sudoku/parser
Package parser reads Sudoku boards in the text format of the sudoku example.
Package parser reads Sudoku boards in the text format of the sudoku example.
sudoku/solver
Package solver solves Sudoku boards by reducing them to exact cover problems for package dlx.
Package solver solves Sudoku boards by reducing them to exact cover problems for package dlx.
twelvetone command
Command twelvetone finds all-interval series: orderings of the n pitches on a circle in which the n-1 steps between neighbours make every interval from 1 to n-1 exactly once.
Command twelvetone finds all-interval series: orderings of the n pitches on a circle in which the n-1 steps between neighbours make every interval from 1 to n-1 exactly once.
vuza command
Command vuza finds the rhythmic canons of a given rhythm: the beats on which copies of the rhythm must enter so that together they strike every beat of a loop exactly once.
Command vuza finds the rhythmic canons of a given rhythm: the beats on which copies of the rhythm must enter so that together they strike every beat of a loop exactly once.
witt command
Command witt searches for Steiner systems: groups of k points, chosen from v points, so that every set of t points lies in exactly one group.
Command witt searches for Steiner systems: groups of k points, chosen from v points, so that every set of t points lies in exactly one group.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL