I'm trying to implement Knuth's 'Algorithm X' to solve exact-cover matrix problems, and have come across a simple matrix which causes the algorithm to fail. Either that, or I haven't understood the description of the algorithm! I strongly suspect the latter, so would be most grateful for someone pointing out where I've gone wrong.
I used the post in this forum titled "Solve the Pentomino puzzle with C++ and dancing links" for the scheme of labeling the matrix, and for the description of the algorithm. See the section "Algorithm X". AFAICS, the algorithm given there is exactly as described elsewhere, e.g. Wikipedia at
Knuth's Algorithm X, and in Knuth's own paper 'Dancing Links'.
The algorithm as I understand it:
1. Find the column with fewest 1s.
2. For that column, choose a row where that column has a 1.
3. For that row, choose the columns where the value in the row is 1, and for each of those columns, remove all rows where the value in the column is 1.
4. Remove the columns selected in step 3.
The test matrix I used is this:
A B C
P 0 0 1
Q 0 1 1
R 1 0 1
S 1 1 0
My interpretation of this, for my example matrix, is:
1. Column with fewest 1s: { A }.
2. Row with 1 in column A: { R }.
3. Columns having a 1 in row R: { A, C }
Remove rows having a 1 in column A: { R, S }
Remove rows having a 1 in column C: { P, Q }
4. Remove columns { A, C }
Step 4 is redundant as the matrix is already empty by then.
This leaves an empty matrix, which is the signal that a solution has been found, consisting of the row in the partial solution, i.e. row R. However, row R by itself is NOT a solution, as it has no 1 in column B. In fact there is no solution containing R; the only valid solution contains rows P and S.
What I have tried:
I've tried reading many different descriptions of 'Algorithm X', and all suggest that I'm doing it the way it should be done. Could there be cases where the algorithm fails, or have I just misunderstood?
Please tell me where my understanding of the algorithm has broken down! :)