1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
#include<cstdio> #include<iostream>
#define MAXN 10 #define MAX_INT 2147483647
using namespace std;
bool flag = false; int matrix[MAXN][MAXN], row[MAXN][MAXN], col[MAXN][MAXN], blo[MAXN][MAXN];
int area[MAXN][MAXN] = { {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 2, 2, 2, 3, 3, 3}, {0, 1, 1, 1, 2, 2, 2, 3, 3, 3}, {0, 1, 1, 1, 2, 2, 2, 3, 3, 3}, {0, 4, 4, 4, 5, 5, 5, 6, 6, 6}, {0, 4, 4, 4, 5, 5, 5, 6, 6, 6}, {0, 4, 4, 4, 5, 5, 5, 6, 6, 6}, {0, 7, 7, 7, 8, 8, 8, 9, 9, 9}, {0, 7, 7, 7, 8, 8, 8, 9, 9, 9}, {0, 7, 7 ,7, 8, 8, 8, 9, 9, 9} };
void solve(int cnt) { if(flag) return ; if( !cnt ) { flag = true; for(int i = 1;i <= 9;i ++) { for(int j = 1;j <= 9;j ++) cout<<matrix[i][j]; cout<<endl; } return ; } int tx, ty, Min = MAX_INT; for(int i = 1;i <= 9;i ++) { for(int j = 1;j <= 9;j ++) { if( !matrix[i][j] ) { int times = 0; for(int k = 1;k <= 9;k ++) if( !row[i][k] && !col[j][k] && !blo[area[i][j]][k] ) times ++; if(times < Min) { Min = times ; tx = i; ty = j; } } } } for(int k = 1;k <= 9;k ++) { if( !row[tx][k] && !col[ty][k] && !blo[area[tx][ty]][k] ) { row[tx][k] = col[ty][k] = blo[area[tx][ty]][k] = 1; matrix[tx][ty] = k; solve(cnt - 1); matrix[tx][ty] = 0; row[tx][k] = col[ty][k] = blo[area[tx][ty]][k] = 0; } } }
int main() { int cases = 0, cnt = 0; cin>>cases; while(cases --) { memset(row, 0, sizeof(row)); memset(col, 0, sizeof(col)); memset(blo, 0, sizeof(blo)); memset(matrix, 0, sizeof(matrix)); flag = false; cnt = 0; for(int i = 1;i <= 9;i ++) { for(int j = 1;j <= 9;j ++) { char ch; cin>>ch; matrix[i][j] = ch - '0'; row[i][matrix[i][j]] = 1; col[j][matrix[i][j]] = 1; blo[area[i][j]][matrix[i][j]] = 1; if( !matrix[i][j] ) cnt ++; } } solve(cnt); } return 0; }
|