基本上就是深搜……
利用3个数组分别来表示行列宫有哪些数存在,用1个数组记录所有需要填数的位置,深搜过去即可
1 #include <stdio.h>
2 #include <string.h>
3 #include <time.h>
4 int rowok[9][10],colok[9][10],miyaok[9][10]; //用来记录行列宫有哪些数字
5 int sudoku[9][9],place[81][2],p,n; //place用来记录哪些位置需要填数
6 int search(int x, int y){
7 int i,j;
8 if(p == n){
9 for(i = 0; i < 9; i++){
10 for(j = 0; j < 9; j++)
11 printf("%d",sudoku[i][j]);
12 puts("");
13 }
14 return 1;
15 }
16 for(i = 1; i < 10; i++)
17 if(!rowok[x][i] && !colok[y][i] && !miyaok[x/3*3+y/3][i]){
18 sudoku[x][y] = i;
19 rowok[x][i] = colok[y][i] = miyaok[x/3*3+y/3][i] = 1;
20 p++;
21 if(search(place[p][0],place[p][1]))
22 return 1;
23 p--;
24 sudoku[x][y] = 0;
25 rowok[x][i] = colok[y][i] = miyaok[x/3*3+y/3][i] = 0;
26 }
27 return 0;
28 }
29 int main (void){
30 long t1;
31 int i,j,T;
32 // freopen("poj2676.in","r",stdin);
33 scanf("%d",&T);
34 while(T--){
35 p = 0;
36 memset(rowok,0,sizeof(rowok));
37 memset(colok,0,sizeof(colok));
38 memset(miyaok,0,sizeof(miyaok));
39 for(i = 0; i < 9; i++){
40 for(j = 0; j < 9; j++){
41 scanf("%1d",&sudoku[i][j]);
42 if(sudoku[i][j]){
43 rowok[i][sudoku[i][j]] = 1;
44 colok[j][sudoku[i][j]] = 1;
45 miyaok[i/3*3+j/3][sudoku[i][j]] = 1;
46 }
47 else{
48 place[p][0] = i;
49 place[p][1] = j;
50 p++;
51 }
52 }
53 }
54 n = p;
55 p = 0;
56 search(place[p][0],place[p][1]);
57 }
58 return 0;
59 }