Algorithm X 是一种递归的,深度优先的回溯的算法,算法的目的是将一个仅由0 1构成的矩阵提取其中的几行,使得这几行构成的新矩阵每列包含且仅包含一个1,适用于精确覆盖问题,如数独,Knuth推荐dance link (dlx)的实现方式
算法具体步骤
- If the matrix A is empty, the problem is solved; terminate successfully.(矩阵为空递归结束)
- Otherwise choose a column c (deterministically).找出1的个数最小的列
- Choose a row r such that Ar, c = 1 (nondeterministically).找出该列中值为1的位置所在的行
- Include row r in the partial solution.提取该行r
- For each column j such that Ar, j = 1,
-
for each row
i such that
A
i, j = 1,
- delete row i from matrix A;与行r值为1的同在一列的行被删除(保证每一列仅有一个1)
- delete column j from matrix A.(r中值为1的列被删除,否则下一次递归时将会因为此列全为0而中断)
-
for each row
i such that
A
i, j = 1,
- Repeat this algorithm recursively on the reduced matrix A
算法例子
For example, consider the exact cover problem specified by the universe U = {1, 2, 3, 4, 5, 6, 7} and the collection of sets = { A, B,C, D, E, F}, where:
-
- A = {1, 4, 7};
- B = {1, 4};
- C = {4, 5, 7};
- D = {3, 5, 6};
- E = {2, 3, 6, 7}; and
- F = {2, 7}.
This problem is represented by the matrix:
-
1 2 3 4 5 6 7 A 1 0 0 1 0 0 1 B 1 0 0 1 0 0 0 C 0 0 0 1 1 0 1 D 0 0 1 0 1 1 0 E 0 1 1 0 0 1 1 F 0 1 0 0 0 0 1
Algorithm X with Knuth's suggested heuristic for selecting columns solves this problem as follows:
Level 0
Step 1—The matrix is not empty, so the algorithm proceeds.
Step 2—The lowest number of 1s in any column is two. Column 1 is the first column with two 1s and thus is selected (deterministically):
-
1 2 3 4 5 6 7 A 1 0 0 1 0 0 1 B 1 0 0 1 0 0 0 C 0 0 0 1 1 0 1 D 0 0 1 0 1 1 0 E 0 1 1 0 0 1 1 F 0 1 0 0 0 0 1
Step 3—Rows A and B each have a 1 in column 1 and thus are selected (nondeterministically).
The algorithm moves to the first branch at level 1…
- Level 1: Select Row A
- Step 4—Row A is included in the partial solution.