HDU- 1426-Sudoku Killer
http://acm.hdu.edu.cn/showproblem.php?pid=1426
#include<iostream> #include<string> using namespace std; const int maxn = 12; int map[maxn][maxn]; bool row_used[maxn][maxn];//所在行 bool low_used[maxn][maxn];//所在列 //int xy_used[maxn][maxn]; int flag; struct Node { bool a[10]; }xy_used[4][4]; void Make_set() { memset(row_used, false, sizeof(row_used)); memset(low_used, false, sizeof(low_used)); memset(xy_used, false, sizeof(xy_used)); } void dfs(int k) { if(k > 81) { //遍历到矩阵外表示已经找到解了 flag = 1; //标记已找到 for(int i=1; i<=9; i++) { for(int j=1; j<9; j++) { printf("%d ", map[i][j]); } printf("%d\n", map[i][9]); } return ; } if(flag == 0) //找到一种解就不再找别的解了,因为只有一种解 { int x = (k-1)/9+1; //行 int y = (k-1)%9+1; //列 k++; if(map[x][y] == 0) //此格需要填数字 { for(int i=1; i<=9; i++) { if(!row_used[x][i] && !low_used[i][y] && !xy_used[(x-1)/3+1][(y-1)/3+1].a[i]) { row_used[x][i]=true; low_used[i][y]=true; xy_used[(x-1)/3+1][(y-1)/3+1].a[i]=true; map[x][y] = i; dfs(k); map[x][y] = 0; row_used[x][i]=false; low_used[i][y]=false; xy_used[(x-1)/3+1][(y-1)/3+1].a[i]=false; } } } else dfs(k); //不需要即跳过寻找下一个 } } int main() { char c[3]; int i, j; int a; int k = 1; while(cin>>c) { Make_set(); if(c[0] == '?') map[1][1] = 0; else { a = map[1][1] = c[0] - '0'; row_used[1][a]=true; low_used[a][1]=true; xy_used[1][1].a[a] = true; } for(i=2; i<=9; i++) { scanf("%s", c); if(c[0] == '?') map[1][i] = 0; else { a = map[1][i] = c[0] - '0'; row_used[1][a]=true; low_used[a][i]=true; xy_used[1][(i-1)/3+1].a[a] = true; } } for(i=2; i<=9; i++) { for(j=1; j<=9; j++) { scanf("%s", c); if(c[0] == '?') map[i][j] = 0; else { a = map[i][j] = c[0] - '0'; row_used[i][a]=true; low_used[a][j]=true; xy_used[(i-1)/3+1][(j-1)/3+1].a[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