模拟+DFS。
1 /* 2780 */ 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 6 char map[10][10]; 7 int visit[10][10][10]; 8 int fn; 9 int fx[6], fy[6]; 10 11 bool dfs(int n) { 12 if (n == 0) 13 return true; 14 int i = fx[n], j = fy[n], k, r; 15 16 for (k=1; k<=9; ++k) { 17 if (!visit[i][j][k]) { 18 map[i][j] = k; 19 visit[i][j][k]++; 20 for (r=0; r<9; ++r) { 21 visit[i][r][k]++; 22 visit[r][j][k]++; 23 visit[i/3*3+k/3][j/3*3+k%3][k]++; 24 } 25 if (dfs(n-1)) 26 return true; 27 visit[i][j][k]--; 28 for (r=0; r<9; ++r) { 29 visit[i][r][k]--; 30 visit[r][j][k]--; 31 visit[i/3*3+k/3][j/3*3+k%3][k]--; 32 } 33 } 34 } 35 return false; 36 } 37 38 bool check() { 39 int i, j, k; 40 int x, y, in; 41 bool f[10]; 42 43 // check row 44 for (i=0; i<9; ++i) { 45 memset(f, false, sizeof(f)); 46 for (j=0; j<9; ++j) { 47 if (map[i][j] && f[map[i][j]]) { 48 return true; 49 } 50 f[map[i][j]] = true; 51 } 52 } 53 54 // check line 55 for (j=0; j<9; ++j) { 56 memset(f, false, sizeof(f)); 57 for (j=0; j<9; ++j) { 58 if (map[i][j] && f[map[i][j]]) { 59 return true; 60 } 61 f[map[i][j]] = true; 62 } 63 } 64 65 // check sub 66 for (x=0; x<9; ++x) { 67 memset(f, false, sizeof(f)); 68 for (y=0; y<9; ++y) { 69 i = x/3*3 + y/3; 70 j = x%3*3 + y%3; 71 if (map[i][j] && f[map[i][j]]) { 72 return true; 73 } 74 f[map[i][j]] = true; 75 } 76 } 77 78 return false; 79 } 80 81 int main() { 82 int t; 83 int i, j, k; 84 bool flag; 85 86 #ifndef ONLINE_JUDGE 87 freopen("data.in", "r", stdin); 88 freopen("data.out", "w", stdout); 89 #endif 90 91 scanf("%d", &t); 92 while (t--) { 93 memset(visit, 0, sizeof(visit)); 94 fn = 1; 95 for (i=0; i<9; ++i) { 96 scanf("%s", map[i]); 97 for (j=0; j<9; ++j) { 98 map[i][j] -= '0'; 99 if (map[i][j] == 0) { 100 fx[fn] = i; 101 fy[fn] = j; 102 ++fn; 103 } else { 104 for (k=0; k<9; ++k) { 105 visit[i][k][map[i][j]]++; 106 visit[k][j][map[i][j]]++; 107 visit[i/3*3+k/3][j/3*3+k%3][map[i][j]]++; 108 } 109 } 110 } 111 } 112 if (check()) { 113 flag = false; 114 } else { 115 flag = dfs(5); 116 } 117 if (flag) { 118 for (i=0; i<9; ++i) { 119 for (j=0; j<9; ++j) 120 map[i][j] += '0'; 121 puts(map[i]); 122 } 123 } else { 124 puts("Could not complete this grid."); 125 } 126 if (t) 127 printf(" "); 128 } 129 130 return 0; 131 }