The Wayback Machine - https://web.archive.org/web/20241006000253/https://www.geeksforgeeks.org/introduction-to-exact-cover-problem-and-algorithm-x/
Open In App

Introduction to Exact Cover Problem and Algorithm X

Last Updated : 28 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
If you have ever tried to create a program for solving Sudoku, you might have come across the Exact Cover problem. In this article, we will discuss what is the exact cover problem and an algorithm “Algorithm X” proposed by Donald Knuth to solve this problem. Given a collection S of subsets of set X, an exact cover is the subset S* of S such that each element of X is contained is exactly one subset of S*. It should satisfy following two conditions –
  • The Intersection of any two subsets in S* should be empty. That is, each element of X should be contained in at most one subset of S*
  • Union of all subsets in S* is X. That means union should contain all the elements in set X. So we can say that S* covers X.
Example (standard representation) – Let S = { A, B, C, D, E, F } and X = {1, 2, 3, 4, 5, 6, 7} such that –
  • A = {1, 4, 7}
  • B = {1, 4}
  • C = {4, 5, 7}
  • D = {3, 5, 6}
  • E = {2, 3, 6 7}
  • F = {2, 7}
Then S* = {B, D, F} is an exact cover, because each element in X is contained exactly once in subsets {B, D, F} . If we union subsets then we will get all the elements of X – [Tex]B \bigcup D \bigcup F = \{ 1,2,3,4,5,6,7\}[\Tex] The Exact cover problem is a decision problem to determine if exact cover exists or not. It is considered to be NP-Complete problem. The problem can be represented in the form of a matrix where the row represents the subsets of S and columns represent the element of X. The above problem can be represented as –
problem matrix

problem matrix

In the context of matrix representation, our exact cover is the selection of rows such that each column contains only single 1 among selected rows. So we can see below that each column have only single 1 among selected rows B, D, F.
exact cover

exact cover

Algorithm X

Donald Knuth proposed an Algorithm X which can find all the solutions to the exact cover problem. Algorithm X can be efficiently implemented by “dancing links” technique proposed by Donald Knuth called DLX. Algorithm X is recursive, depth-first, backtracking algorithm. It is non-deterministic in nature, that means for the same input, it can exhibit different behaviors on a different run. Following is the pseudo code for Algorithm X –
 
1. If the matrix A has no columns, the current partial solution
   is a valid solution; terminate successfully. 
2. Otherwise, choose a column c (deterministically). 
3. Choose a row r such that A[r] = 1 (nondeterministically). 
4. Include row r in the partial solution. 
5. For each column j such that A[r][j] = 1,
        for each row i such that A[i][j] = 1, 
            delete row i from matrix A. 
      delete column j from matrix A. 
6. Repeat this algorithm recursively on the reduced matrix A. 
Non-deterministic choice of r means, algorithm copy itself into sub algorithm. Each sub algorithm inherit original matrix A but reduces it with respect to chosen r (we will see this shortly in example) The sub algorithm forms a search tree with the original problem at the root and each level k have sub algorithm correspond to the rows chosen in previous level (just like the n-queen search space). If chosen column c is entirely zero then there are no sub algorithms and the process terminated unsuccessfully. Knuth suggests that we should choose the column with the minimum number of 1’s in it. If no column left, then we know we have found our solution. Example Consider the above example, we will apply Algorithm X on it to find the exact cover – Level – 0 Step-1: Our matrix is not empty, it has columns then proceed Step-2: The first column which has minimum number of 1’s in it is C-1 so we will select it Step-3: Rows A and B have 1 at C-1 so they are selected. So now the algorithm moves to first branch at level 1 Level – 1 (Select row A) Step-4: Select row A and add it to partial solutions Step-5: Row A has 1 in column 1, 4, 7 C-1 have 1 in row A and B, C-4 have 1 in A, B and C, C-7 have 1 in row A, C, E, and F. So column 1, 4, 7 and rows A, B, C, E and F should be removed. Step 1 – Matrix is not empty so proceed Step 2 – The first column which has minimum number of 1’s is C-2 Since column C-2 have no 1’s in it, our search will terminate here unsuccessfully. Now our algorithm will backtrack at level 0 and proceed with row B at second branch at level 1 Level – 1(Select row B) Step – 4: Select row B and add it to partial solutions Step – 5: Row B has 1 in column C-1 and C-4 C-1 have 1’s at row A and B. C-4 have 1’s in row A, B and C. So C-1, C-2 and Row A, B, C will be removed from the matrix. Now we repeat algorithm – Step-1: Matrix is not empty, proceed Step-2: C-5 has a minimum number of 1’s in it, so it is chosen. Step-3: Row D has 1 at C-5, so it is chosen Now algorithm moves to 1st branch at level 2 with matrix having row D, E and F Level-2(Select row D) Step-4: Row D is chosen and added to partial solution. Step-5: C-3, C-5, C-6 have 1 at row D At C-3 row D and E have 1, at C-5 row D have 1 and at C-6 row D, E have 1. So these rows and columns should be deleted and we left with a matrix having only row F and column 2, 7. Now we will repeat the algorithm – Step-1: Matrix is not empty so proceed Step-2: C-2 is the first column having a minimum number if 1’s in it. So it is chosen Step-3: Row F have 1 at C-2 so it is chosen. Now algorithm will move to the first branch at level 3. Level – 3(Select row F) Step-4: Row F is added to the partial solution Step-5: C-2 and C-7 have 1 at row F. C-2 have 1 at row F, C-7 have 1 at row F So C2,C7 and row F should be removed. After removing we will left with an empty matrix so our search can terminate here successfully and we have our exact cover {B, D,F} sub algorithm backtrack at level 2 and since there is no row left at level 3. It further backtracks at level 1 . Since at level 1 there is no row left to our algorithm terminated. In next article, we will discuss how to implement DLX efficiently to solve Exact Cover. References


Similar Reads

Implementation of Exact Cover Problem and Algorithm X using DLX
In the article Exact Cover Problem and Algorithm X | Set 1 we discussed the Exact Cover problem and Algorithm X to solve the Exact cover problem. In this article, we’ll discuss the implementation details of Algorithm X using Dancing Links Technique (DLX) proposed by Dr Donald E. Knuth in his paper “Dancing Links” Dancing Link Technique Dancing link
10 min read
Introduction and Approximate Solution for Vertex Cover Problem
A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either 'u' or 'v' is in the vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. Given an undirected graph, the vertex cover problem is to find minimum size vertex cover. The following are some exa
10 min read
Greedy Approximate Algorithm for Set Cover Problem
Given a universe U of n elements, a collection of subsets of U say S = {S1, S2...,Sm} where every subset Si has an associated cost. Find a minimum cost subcollection of S that covers all elements of U. Example: U = {1,2,3,4,5} S = {S1,S2,S3} S1 = {4,1,3}, Cost(S1) = 5 S2 = {2,5}, Cost(S2) = 10 S3 = {1,4,3,2}, Cost(S3) = 3 Output: Minimum cost of se
6 min read
Vertex Cover Problem (Dynamic Programming Solution for Tree)
A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complete. But it can be solved in polynomial time for tre
15+ min read
Shortest Superstring Problem | Set 2 (Using Set Cover)
Given a set of n strings S, find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string. Examples: Input: S = {"001", "01101", "010"} Output: 0011010 Input: S = {"geeks", "quiz", "for"} Output: geeksquizfor Input: S = {"catg", "ctaagt", "gcta", "ttca", "atgca
3 min read
Hungarian Algorithm for Assignment Problem | Set 1 (Introduction)
Let there be n agents and n tasks. Any agent can be assigned to perform any task, incurring some cost that may vary depending on the agent-task assignment. It is required to perform all tasks by assigning exactly one agent to each task and exactly one task to each agent in such a way that the total cost of the assignment is minimized. Example: You
15+ min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
Minimum count of subintervals to cover a given time duration
Given an array of intervals[], the task is to find the minimum count of subintervals needed to cover a given time duration. Each interval represents a segment of time that starts at a specific point in time (start time) and ends at another specific point in time (end time). The intervals may overlap and have varying lengths. If it's impossible to c
8 min read
Count number of steps to cover a distance if steps can be taken in powers of 2
Given a distance K to cover, the task is to find the minimum steps required to cover the distance if steps can be taken in powers of 2 like 1, 2, 4, 8, 16........Examples : Input : K = 9 Output : 2 Input : K = 343 Output : 6 The minimum steps required can be calculated by reducing K by the highest power of 2 in each step which can be obtained by co
3 min read
Proof that vertex cover is NP complete
Prerequisite - Vertex Cover Problem, NP-Completeness Problem - Given a graph G(V, E) and a positive integer k, the problem is to find whether there is a subset V’ of vertices of size at most k, such that every edge in the graph is connected to some vertex in V’. Explanation - First let us understand the notion of an instance of a problem. An instan
5 min read
Program to Calculate the Edge Cover of a Graph
Given the number of vertices N of a graph. The task is to determine the Edge cover.Edge Cover: Minimum number of edges required to cover all vertex is known as Edge Cover. Examples: Input : N = 5 Output : 3 Input : N = 4 Output : 2 Example 1: For N = 5 vertices, Edge Cover is: 3 (Choosing the edges marked in Red, all of the vertices will get covere
3 min read
Minimum cost to cover the given positions in a N*M grid
Given a n*m grid and the position of some poles to be painted in the grid, the task is to find the minimum cost to paint all the poles. There is no cost involved in moving from one row to the other, whereas moving to an adjacent column has 1 rupee cost associated with it. Examples: Input: n = 2, m = 2, noOfPos = 2 pos[0] = 0, 0 pos[1] = 0, 1 Output
4 min read
Count number of ways to cover a distance | Set 2
Given a distance N. The task is to count the total number of ways to cover the distance with 1, 2 and 3 steps.Examples: Input: N = 3 Output: 4 All the required ways are (1 + 1 + 1), (1 + 2), (2 + 1) and (3).Input: N = 4 Output: 7 Approach: In previous article, a recursive and dynamic programming based approach has been discussed. Here we will reduc
5 min read
Minimum time required to cover a Binary Array
Given an integer N which represents the size of a boolean array that is initially filled with 0, and also given an array arr[] of size K consisting of (1-based) indices at which '1' are present in the boolean array. Now, at one unit of time the adjacent cells of the arr[i] in the boolean array become 1 that is 010 becomes 111. Find the minimum time
8 min read
Minimum number of points required to cover all blocks of a 2-D grid
Given two integers N and M. The task is to find the minimum number of points required to cover an N * M grid. A point can cover two blocks in a 2-D grid when placed in any common line or sideline. Examples: Input: N = 5, M = 7 Output: 18Input: N = 3, M = 8 Output: 12 Approach: This problem can be solved using Greedy Approach. The main idea is to ob
4 min read
Maximum number of tiles required to cover the floor of given size using 2x1 size tiles
Given a floor of size MxN size and tiles of size 2x1, the task is to find the maximum number of tiles required to cover the floor as much as possible of size MxN size.Note: A tile can either be placed horizontally or vertically and no two tiles should overlap. Examples: Input: M = 2, N = 4Output: 4Explanation:4 tiles are needed to cover the floor.
4 min read
Minimum number of pairs required to be selected to cover a given range
Given an array arr[] consisting of N pairs and a positive integer K, the task is to select the minimum number of pairs such that it covers the entire range [0, K]. If it is not possible to cover the range [0, K], then print -1. Examples : Input: arr[] = {{0, 3}, {2, 5}, {5, 6}, {6, 8}, {6, 10}}, K = 10Output: 4Explanation: One of the optimal ways i
10 min read
Minimum jumps to cover given elements from circular sequence of 1 to n
Given a circular connected array consisting of elements from 1 to n. Starting from 1st element, you can jump from any element to any other element which is x distance apart and in the right direction, the task is to find the minimum jumps required to cover all the given elements of list m if you can choose any value of x. Examples: Input: n = 5, m
8 min read
Number of squares of side length required to cover an N*M rectangle
Given three numbers N,M ,a . Find Number of squares of dimension a*a required to cover N*M rectangle. Note: It's allowed to cover the surface larger than the rectangle, but the rectangle has to be covered.It's not allowed to break a square.The sides of squares should be parallel to the sides of the rectangle.Examples: Input: N = 6, M = 6, a = 4Outp
8 min read
Minimum number of intervals to cover the target interval
Given an array A[] consisting of N intervals and a target interval X, the task is to find the minimum number of intervals from the given array A[] such that they entirely cover the target interval. If there doesn't exist any such interval then print "-1". Examples: Input: A[] = {{1, 3}, {2, 4}, {2, 10}, {2, 3}, {1, 1}}, X = {1, 10}Output: 2Explanat
15+ min read
Set cover is NP Complete
Problem: Given a ground Set X, an integer k, and a collection of subsets Si of X, the problem is to identify if there exists a collection of subsets whose union is X, with size at most k. Proof: An instance of the problem is an input specified to the problem. An instance of the Set Cover problem is a Ground set X, an integer k and a collection of s
3 min read
Count minimum number of fountains to be activated to cover the entire garden
There is a one-dimensional garden of length N. In each position of the N length garden, a fountain has been installed. Given an array a[]such that a[i] describes the coverage limit of ith fountain. A fountain can cover the range from the position max(i - a[i], 1) to min(i + a[i], N). In beginning, all the fountains are switched off. The task is to
13 min read
Finding minimum vertex cover size of a graph using binary search
A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. There may be a lot of vertex covers possible for a graph. Problem Find the size of the minimum size vertex cover, that is, cardinality of a vertex cover with minimum cardinality, for an undirected con
15+ min read
Minimum distance to travel to cover all intervals
Given many intervals as ranges and our position. We need to find minimum distance to travel to reach such a point which covers all the intervals at once. Examples: Input : Intervals = [(0, 7), (2, 14), (4, 6)] Position = 3 Output : 1 We can reach position 4 by travelling distance 1, at which all intervals will be covered. So answer will be 1 Input
8 min read
Minimum lines to cover all points
Given N points in 2-dimensional space, we need to print the count of the minimum number of lines which traverse through all these N points and which go through a specific (xO, yO) point also.Examples: If given points are (-1, 3), (4, 3), (2, 1), (-1, -2), (3, -3) and (xO, yO) point is (1, 0) i.e. every line must go through this point. Then we have
9 min read
Minimum tiles of sizes in powers of two to cover whole area
Given an area of N X M. You have the infinite number of tiles of size 2i X 2i, where i = 0, 1, 2,... so on. The task is to find the minimum number of tiles required to fill the given area with tiles.Examples: Input : N = 5, M = 6. Output : 9 Area of 5 X 6 can be covered with minimum 9 tiles. 6 tiles of 1 X 1, 2 tiles of 2 X 2, 1 tile of 4 X 4. Inpu
8 min read
Minimize Acceleration of Car to Cover Track
Given an array times[] of size n and a positive integer trackLength, where each element in times[] represent exact time where the car's acceleration will be increased to k meters per second and then decreased by 1 meter per second until it reaches 0. The task is to minimize the acceleration of car (i.e, k) to cover the trackLength. Examples: Input:
9 min read
Minimum queens required to cover all the squares of a chess board
Given the dimension of a chess board (N x M), determine the minimum number of queens required to cover all the squares of the board. A queen can attack any square along its row, column or diagonals. Examples: Input : N = 8, M = 8Output : 5Layout : Q X X X X X X X X X Q X X X X X X X X X Q X X X X Q X X X X X X X X X Q X X X X X X X X X X X X X X X
14 min read
Minimum rectangles to cover all points
Given a 2D array points[][], where points[i] = [xi, yi]. The task is to find the minimum number of rectangles of width `w` or less needed to cover all points in a given 2D array, where each rectangle's lower end is at (x1, 0) and upper end at (x2, y2) with x1 = 0. A point is covered if it's within or on the rectangle's boundary. A point can be cove
4 min read
Minimum steps needed to cover a sequence of points on an infinite grid
Given an infinite grid, initial cell position (x, y) and a sequence of other cell position which needs to be covered in the given order. The task is to find the minimum number of steps needed to travel to all those cells. Note: Movement can be done in any of the eight possible directions from a given cell i.e from cell (x, y) you can move to any of
7 min read
Practice Tags :