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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
| #include <queue> #include <utility> #include <cstdio> #include <algorithm>
using namespace std;
unsigned countbit(unsigned x) noexcept { unsigned cnt = 0; while (x) { cnt++; x -= (x & -x); } return cnt; }
int a[15][15]; int b[15][15]; int maxn = -1;
unsigned row[15], col[15], hou[15]; constexpr int grow(int x, int y) noexcept { return x; }
constexpr int gcol(int x, int y) noexcept { return y; }
constexpr int ghou(int x, int y) noexcept { return (x - 1) / 3 * 3 + (y - 1) / 3 + 1; }
constexpr int rval(int x, int y) noexcept { return min(min(x, 10 - x), min(y, 10 - y)) + 5; }
int vval(int x, int y) noexcept { return a[x][y] ? 100 : countbit(~((row[grow(x, y)]) | (col[gcol(x, y)]) | (hou[ghou(x, y)]))); }
pair<int, int> calc() { int minn = 1000, x, y; for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { if (vval(i, j) < minn) { minn = vval(i, j); x = i; y = j; } } } return { x, y }; }
int dfs() { int x, y; auto res = calc(); x = res.first; y = res.second; if (a[x][y]) { copy(&a[0][0], &a[14][15], &b[0][0]); return 1; } int sum = 0; for (int i = 9; i >= 1; i--) { if (row[grow(x, y)] & (1u << (i - 1))) continue; if (col[gcol(x, y)] & (1u << (i - 1))) continue; if (hou[ghou(x, y)] & (1u << (i - 1))) continue;
row[grow(x, y)] |= (1u << (i - 1)); col[gcol(x, y)] |= (1u << (i - 1)); hou[ghou(x, y)] |= (1u << (i - 1));
a[x][y] = i; sum += dfs(); a[x][y] = 0; row[grow(x, y)] &= ~(1u << (i - 1)); col[gcol(x, y)] &= ~(1u << (i - 1)); hou[ghou(x, y)] &= ~(1u << (i - 1)); } return sum; }
int main() { int t; scanf("%d", &t); while (t--) { fill(a[0] + 0, a[14] + 15, 0); fill(row, row + 15, 0); fill(col, col + 15, 0); fill(hou, hou + 15, 0); bool flag = false; for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { scanf("%d", a[i] + j); if (a[i][j]) { if (row[grow(i, j)] & (1 << (a[i][j] - 1))) flag = true; if (col[gcol(i, j)] & (1 << (a[i][j] - 1))) flag = true; if (hou[ghou(i, j)] & (1 << (a[i][j] - 1))) flag = true; row[grow(i, j)] |= (1u << (a[i][j] - 1)); col[gcol(i, j)] |= (1u << (a[i][j] - 1)); hou[ghou(i, j)] |= (1u << (a[i][j] - 1)); } } } if (flag) goto ee; int d; printf("%d\n", d = dfs()); if (d == 1) { for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { printf("%d%c", b[i][j], " \n"[j == 9]); } } } continue; ee: printf("0\n"); } return 0; }
|