Sudoku
problem ' s Link:
http://poj.org/problem?id=2676
Mean:
Slightly
Analyse:
Log all empty locations, determine whether the current empty position can fill a number, and then direct DFS, notice from the forward search, the time is much faster than the positive searching. 16ms Water Over
Time Complexity:o (n)
Source Code:
//Memory Time//1347K 0MS//by:crazyacking//2015-04-10-14.30#include <map>#include<queue>#include<stack>#include<cmath>#include<cstdio>#include<vector>#include<string>#include<cstdlib>#include<cstring>#include<climits>#include<iostream>#include<algorithm>#defineMAXN 1000010#defineLL Long Longusing namespacestd;structnode{intx, y;}; Node b[ -];intg[9][9];intidx;BOOLFlag;voidinput () {Chars[Ten]; IDX=0; Flag=0; for(intI=0;i<9;++i) {scanf ("%s", s); for(intj=0;j<9;++j) {G[i][j]=s[j]-'0'; if(g[i][j]==0) {b[idx].x=i; B[idx].y=J; IDX++; }}} idx--;}BOOLCheck (intXintYintnum) { for(intI=0;i<9;++i) {if(G[x][i]==num)return false; if(G[i][y]==num)return false; } intsta_x=x/3*3; intsta_y=y/3*3; for(inti=sta_x;i<sta_x+3;++i) { for(intj=sta_y;j<sta_y+3;++j) {if(G[i][j]==num)return false; } } return true;}voidDFS (intN) { if(n==-1) {flag=1; return ; } intx=b[n].x; inty=b[n].y; for(intI=1; i<=9;++i) {if(Check (x,y,i)) {G[x][y]=i; DFS (n-1); if(flag)return ; G[x][y]=0; } } return;}voidoutput () { for(intI=0;i<9;++i) { for(intj=0;j<9;++j) {printf ("%d", G[i][j]); } puts (""); }}intMain () {intCas; scanf ("%d",&Cas); while(cas--) {input (); DFS (IDX); Output (); } return 0;}
View Code
Search---Sudoku solution POJ 2676 Sudoku