is also a simple pruning of Dfs. Record all 0 position, fill in order, when found that a space can be selected to fill in the number has not been, indicating that the branch is invalid, cut off.
Not a problem, but still spent a lot of time, the problem is mainly in the details, the row and column coordinates reversed, 3 times 3 small lattice position judgment. Write procedures must be careful.
#include <iostream>using namespacestd;Const intMax_r =9;intMap[max_r +1][max_r +1];intZero_pos[max_r * max_r][2];intPossible_digits[max_r * max_r][9];intzero_cnt;intSetpossibledigits (intXintYints) { BOOLpossible[Ten]; memset (Possible,0,sizeof(possible)); for(inti =1; I <= max_r; i++) {Possible[map[i][x]]=true; Possible[map[y][i]]=true; } intSUBX = (X-1) /3; intSuby = (Y-1) /3; for(inti = SUBX *3+1; I <= SUBX *3+3; i++){ for(intj = Suby *3+1; J <= Suby *3+3; J + +) {Possible[map[j][i]]=true; } } intCNT =0; for(inti =1; I <=9; i++){ if(!Possible[i]) possible_digits[s][cnt++] =i; } returnCNT;}BOOLDfsintStep) { if(Step = =zero_cnt) { return true; } intCurX = zero_pos[step][1], CurY= zero_pos[step][0]; intpossible_cnt =setpossibledigits (CurX, CurY, step); if(possible_cnt = =0){ return false; } for(inti =0; i < possible_cnt; i++) {Map[cury][curx]=Possible_digits[step][i]; if(Dfs (step +1)) return true; ElseMap[cury][curx]=0; } return false;}intMain () {intT; CIN>>T; while(t--) {memset (map,0,sizeof(map)); memset (Zero_pos,0,sizeof(Zero_pos)); memset (Possible_digits,0,sizeof(possible_digits)); Zero_cnt=0; for(inti =1; I <= max_r; i++){ for(intj =1; J <= Max_r; J + +){ Charch; CIN>>ch; MAP[I][J]= CH-'0'; if(Map[i][j] = =0) {zero_pos[zero_cnt][0] =i; Zero_pos[zero_cnt++][1] =J; }}} DFS (0); for(inti =1; I <= max_r; i++){ for(intj =1; J <= Max_r; J + +) {cout<<Map[i][j]; } cout<<Endl; } } return 0;}
poj2676 (Sudoku)