dfs + 回溯
数独
#include <iostream> using namespace std; struct Node { int x, y; }ns[85]; int cntSum, ca=1; int mp[10][10]; bool init() { int i, j; char ch[5]; cntSum = 0; for( i=0; i<9; ++i ) { for( j=0; j<9; ++j ) { if( scanf( "%s", ch ) == EOF ) return 0; if( ch[0] == '?' ) { ns[cntSum].x = i; ns[cntSum++].y = j; mp[i][j] = 0; } else { mp[i][j] = ch[0] - '0'; } } } } bool canPut( int deep, int v ) { int x, y, i, j, a, b; x = ns[deep].x; y = ns[deep].y; for( i=0; i<9; ++i ) if( i != y && mp[x][i] == v ) return 0; for( i=0; i<9; ++i ) if( i != x && mp[i][y] == v ) return 0; a = x / 3; b = y / 3; for( i=a*3; i<=a*3+2; ++i ) { for( j=b*3; j<=b*3+2; ++j ) { if( i!=x && j!=y && mp[i][j] == v ) return 0; } } return 1; } bool dfs( int deep) { if( deep >= cntSum ) return 1; for( int i=1; i<=9; ++i ) { if( canPut( deep, i ) ) { mp[ns[deep].x][ns[deep].y] = i; if( dfs( deep+1) ) return 1; mp[ns[deep].x][ns[deep].y] = 0; } } return 0; } void solve() { int i; for( i=1; i<=9; ++i ) { if( canPut(0, i) ) { mp[ns[0].x][ns[0].y] = i; if( dfs( 1 ) ) return; mp[ns[0].x][ns[0].y] = 0; } } } void Print() { int i, j; if( ca != 1 ) printf( "\n" ); ++ ca; for( i=0; i<9; ++i ) { for( j=0; j<9; ++j ) { if( j!= 0 ) putchar( ' ' ); printf( "%d", mp[i][j] ); } printf( "\n" ); } } int main() { // freopen( "c:/aaa.txt", "r", stdin ); int i, j; char ch[5]; while( init() ) { solve(); Print(); } return 0; }