Although DLX can improve efficiency .... But for NPC, there is no need to be too efficient, and there is only one point of test.
So as long as Dfs fills in, until the spaces are all filled up, be aware of the update and recovery of global variables in DFS.
As for the method of storage, just consider the non-repetition of each small block of each row in each column.
#include <iostream>#include<cstring>using namespacestd;intCNT =0;//indicates the number of remaining spaces to fillstructpoint{intx, y;}; Point epts[Bayi+5];//Storing spacesBOOLr[Ten][Ten],//R[i][k] Indicates if there is a number k in line Ic[Ten][Ten],//C[j][k] Indicates whether there is a number k in column Jsq[4][4][Ten];//Sq[t][t][k] Indicates whether there is a number k in this small piece of t,t.intg[Ten][Ten];//storing the entire input sudoku is actually not necessary.intAns =0;voidDfsintcur) { if(Ans >1) return; if(Cur <0) {//If all the blanks are filled, BOOLOK =true; //Be sure to judge legality ... for(inti =0; I <9; ++i) { for(intj=1; J <=9; ++j) { if((!r[i][j]) | | (!c[i][j]) | | (!sq[i/3][i/3][j]) OK=false; } } if(ok) ans++; return; } intx =epts[cur].x; inty =epts[cur].y; for(intK =1; K <=9; ++k) {if(R[x][k] | | c[y][k] | | sq[x/3][y/3][k])Continue; R[X][K]= C[y][k] = sq[x/3][y/3][K] =true;//Set Deposit//G[x][y] = k;DFS (cur-1); R[X][K]= C[y][k] = sq[x/3][y/3][K] =false;//Cancel Deposit } return;}intMainintargcChar Const*argv[]) { intT; CIN>>u; for(intt =0; T < T; ++t) {cnt=0;//InitializeAns =0; Memset (R,false,sizeof(R)); Memset (c,false,sizeof(c)); memset (Sq,false,sizeof(SQ)); for(inti =0; I <9; ++i) { for(intj=0; J <9; ++j) { intK; CIN>>K; G[I][J]=K; if(k>0) R[i][k]= C[j][k] = sq[i/3][j/3][K] =true; Elseepts[cnt+ +] = (point) {i,j};//Build Object } } //starting with the last space Dfs tries to fillDFS (cnt-1); if(ans==1) {cout<<"Yes"<<Endl; } Elsecout<<"No"<<Endl; } return 0;}
"Algorithmic Learning Notes" 61. Backtracking DFS SJTU OJ 1106 Sudoku