数独问题
#include <bits/stdc++.h> using namespace std; const int maxn = 20; int ans[maxn][maxn]={ {8,0,4,0,9,0,3,2,0}, {0,0,1,0,0,0,8,0,0}, {6,0,0,0,0,8,0,9,7}, {5,0,0,0,3,0,2,0,0}, {7,0,0,0,0,0,0,0,0}, {0,0,9,0,0,5,0,4,0}, {0,0,7,8,1,0,9,0,0}, {1,0,0,0,0,4,0,0,0}, {4,0,3,0,6,9,0,7,0}, }; bool hashcol[maxn][maxn]; bool hashrow[maxn][maxn]; bool hashblo[maxn][maxn]; void upda(int x,int y,int z) { hashcol[x][ans[x][y]]=z; hashrow[y][ans[x][y]]=z; hashblo[x/3*3+y/3][ans[x][y]]=z; } bool dfs(int x,int y) { while(ans[x][y]) { if(x==8&&y==8)return true; if(y==8)y=0,x++; else y++; } for(int k=1;k<=9;k++) { if(!hashcol[x][k]&&!hashrow[y][k]&&!hashblo[x/3*3+y/3][k]) { ans[x][y]=k; upda(x,y,1); if(dfs(x,y))return true; upda(x,y,0); ans[x][y]=0; } } return false; } int main() { for(int x=0;x<9;x++) for(int y=0;y<9;y++) upda(x,y,1); if(dfs(0,0)) { for(int x=0;x<9;x++) { for(int y=0;y<9;y++) cout<<ans[x][y]<<" "; cout<<endl; } } else { cout<<"no answer!"<<endl; } return 0; }