The typical search problem is mainly time optimization. I used three secondary arrays to record information row [I] [k] = 1, indicating that row I number k has been used, col [j] [k] = 1 The number k in column j has been used, and blo [I] [k] indicates that the number k in column I has been used
There is also a very important optimization (it may time out or be very slow if there is no optimization, as many in the POJ discussion board say that the search is time-out, and the search is 0 ms, this is indeed a usable method, but it has a certain degree of randomness). Each time you fill in a number, scan the entire matrix first to find the location where the number with the minimum number is 0, this will make the search tree as thin as possible, and the effect will be very obvious.
Code
/* Poj 2676236K0MS */# include
# Include
# Define MAXN 10 # define MAX_INT 2147483647 using namespace std; bool flag = false; int matrix [MAXN] [MAXN], row [MAXN] [MAXN], col [MAXN] [MAXN], blo [MAXN] [MAXN]; // use int to judge faster than bool! Int area [MAXN] [MAXN] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 2, 2, 2, 3, 3}, {0, 1, 1, 1, 2, 2, 2, 3, 3}, {0, 1, 1, 1, 2, 2, 2, 3, 3, 3}, {0, 4, 4, 4, 5, 5, 5, 6, 6, 6}, {0, 4, 4, 4, 5, 5, 5, 6, 6}, {0, 4, 4, 4, 5, 5, 5, 6, 6, 6}, {0, 7, 7, 7, 8, 8, 9, 9}, {0, 7, 7, 7, 8, 8, 8, 9, 9, 9}, {0, 7, 7, 7, 8, 8, 8, 9, 9, 9}; void solve (int cnt) {if (flag) return; if (! Cnt) {flag = true; for (int I = 1; I <= 9; I ++) {for (int j = 1; j <= 9; j ++) cout <
> Cases; while (cases --) {memset (row, 0, sizeof (row); memset (col, 0, sizeof (col); memset (blo, 0, sizeof (blo); memset (matrix, 0, sizeof (matrix); flag = false; cnt = 0; for (int I = 1; I <= 9; I ++) {for (int j = 1; j <= 9; j ++) {char ch; cin> ch; matrix [I] [j] = ch-'0'; row [I] [matrix [I] [j] = 1; col [j] [matrix [I] [j] = 1; blo [area [I] [j] [matrix [I] [j] = 1; if (! Matrix [I] [j]) cnt ++ ;}} solve (cnt) ;}return 0 ;}