题目链接
Description
Input
Output
Sample Input
7 1 2 ? 6 ? 3 5 8 ? 6 5 2 ? 7 1 ? 4 ? ? 8 5 1 3 6 7 2 9 2 4 ? 5 6 ? 3 7 5 ? 6 ? ? ? 2 4 1 1 ? 3 7 2 ? 9 ? 5 ? ? 1 9 7 5 4 8 6 6 ? 7 8 3 ? 5 1 9 8 5 9 ? 4 ? ? 2 3
Sample Output
7 1 2 4 6 9 3 5 8 3 6 5 2 8 7 1 9 4 4 9 8 5 1 3 6 7 2 9 2 4 1 5 6 8 3 7 5 7 6 3 9 8 2 4 1 1 8 3 7 2 4 9 6 5 2 3 1 9 7 5 4 8 6 6 4 7 8 3 2 5 1 9 8 5 9 6 4 1 7 2 3
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<vector> #include<cmath> #include<queue> #include<stack> #include<map> #include<set> #include<algorithm> using namespace std; const int maxn=100010; const int INF=1000000100; const int dir1[4][2] = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; const int dir2[4][2] = {{0, 1}, {0, -1}, {0, 1}, {0, -1}}; const int dir3[4][2] = {{1, 0}, {1, 0}, {-1, 0}, {-1, 0}}; #define PI acos-1.0 #define N 510 char g[N][N]; int k, flag, vis[N]; void DFS (int n); void Print (); int check (int x, int y, int i); int main () { int i, j, p = 0; while (cin >> g[0][0]) { k = 0, flag = 0; if (p++) cout << endl; memset (vis, 0, sizeof (vis)); if (g[0][0] == '?') vis[k++] = 0; for (i=0; i<9; i++) { for (j=0; j<9; j++) { if (i || j) { cin >> g[i][j]; if (g[i][j] == '?') vis[k++] = i * 9 + j; } } } DFS (0); } return 0; } void DFS (int n) { if (n >= k) { flag = 1; Print (); return; } int x = vis[n]/9, y = vis[n]%9; for (int i=1; i<=9; i++) { if (check (x, y, i)) { g[x][y] = i + '0'; DFS (n+1); if (flag) return; g[x][y] = '?'; } } } int check (int x, int y, int i) { for (int j=0; j<9; j++) if (g[x][j] == i + '0' || g[j][y] == i + '0') return 0; int dx = x / 3, dy = y / 3; for (int j=dx*3; j<dx*3+3; j++) for (int j1=dy*3; j1<dy*3+3; j1++) if (g[j][j1] == i + '0') return 0; return 1; } void Print () { for (int i=0; i<9; i++) { for (int j=0; j<8; j++) cout << g[i][j] << ' '; cout << g[i][8] << endl; } }