公司搞了个小活动,让大家玩数独游戏,作为一个程序员,第一考虑就是用 C++ 穷举,于是就有了下面的代码: #include "stdafx.h" bool check( int buf[9][9], int j, int i ) { int v=buf[j][i]; // 检测横向是否有冲突 for( int l=0; l<9; l++ ) if( (l!=i) && (buf[j][l]==v) ) return true; // 检测纵向是否冲突 for( int l=0; l<9; l++ ) if( (l!=j) && (buf[l][i]==v) ) return true; // 检测小格是否重复 int x=0; if( j > 2 ) x++; if( j > 5 ) x++; int y=0; if( i > 2 ) y++; if( i > 5 ) y++; bool b[9]; memset( b,0, sizeof(b) ); for( int x1=0; x1<3; x1++ ){ for( int y1=0; y1<3;y1++ ){ int X=x*3+x1; int Y=y*3+y1; int v=buf[X][Y]; if( v!=0 ){ if( b[ v-1 ] ) return true; b[ v-1 ]=true; } } } return false; } int _tmain(int argc, _TCHAR* argv[]) { using namespace std; int num[9][9]; // 读取原始数据 ifstream txt( "original.txt" ); vector< pair<int, int> > blacks; // 空格 for( int j=0; j<9; j++){ for( int i=0; i<9; i++ ){ txt >> num[j][i]; cout << " " << num[j][i]; if( 0==num[j][i] ){ blacks.push_back( make_pair(j,i) ); } } cout << endl; } int buf[9][9]; memcpy( buf, num, sizeof(num) ); cout << "black:" << blacks.size() << endl; for( int i=0; i<blacks.size(); i++ ){ pair<int,int> o=blacks[i]; for(;;){ if( ++buf[o.first][o.second] > 9 ){ buf[o.first][o.second]=0; i--; if( i<0 ){ cout << "no answer." << endl; system("pause"); return 0; } o=blacks[i]; }else{ if( !check( buf, o.first, o.second ) ) break; } }; } cout << "answer: " << endl; for( int j=0; j<9; j++){ for( int i=0; i<9; i++ ){ cout << " " << buf[j][i]; } cout << endl; } system("pause"); return 0; } 输入文件 orginal.txt : 0 4 0 0 2 1 0 8 0 7 0 5 0 4 9 3 1 0 0 2 3 0 0 0 0 0 9 5 0 0 2 9 0 0 0 0 0 0 8 0 6 0 1 0 0 0 0 0 0 1 8 0 0 3 8 0 0 0 0 0 7 9 0 0 5 7 9 8 0 6 0 1 0 9 0 1 5 0 0 3 0 0 代表空格。