Question:
Http://poj.org/problem? Id = 2676
Question:
Sudoku, 1-9 in each row, 1-9 in each column, 1-9 in every 3x3 small cells, no duplicates
Method: dancing links (16 ms) or DFS brute force search (400-900 ms)
Dancing links (DLX) is an algorithm used to solve the problem of precise matrix coverage. The algorithm efficiency is very high.
The problems solved by using DLX must be converted to precise matrix coverage:
1. DLX details:
Http://wenku.baidu.com/view/d8f13dc45fbfc77da269b126.html
2. Conversion Method:
Very detailed explanation: http://www.cnblogs.com/grenet/p/3163550.html
Constraint 1: only one number can be entered for each grid: DLX. Link (T, encode (0, I, j ));
Constraint 2: each row needs 1-9: DLX. Link (T, encode (1, I, K-1 ));
Constraint 3: each column needs 1-9: DLX. Link (T, encode (2, j, k-1 ));
Constraint 4: 1-9: DLX for every 3*3 grids. link (T, encode (3, (I/3) * 3 + J/3, k-1 ));
1 void build() 2 { 3 for (int i = 0; i < 9; i++) 4 for (int j = 0; j < 9; j++) 5 for (int k = 1; k <= 9; k++) 6 if (mtx[i][j] == ‘0‘ || mtx[i][j] == k + ‘0‘) 7 { 8 int t = encode(i, j, k - 1); 9 dlx.Link(t, encode(0, i, j));10 dlx.Link(t, encode(1, i, k - 1));11 dlx.Link(t, encode(2, j, k - 1));12 dlx.Link(t, encode(3, (i / 3) * 3 + j / 3, k - 1));13 }14 }
DLX template (converted from kuangbin (http://www.cnblogs.com/kuangbin/p/3752854.html )):
DLX template (from kuangbin)
Code:
Poj 2676
Poj 2676 Sudoku (search, dancing links)