Guest User

Untitled

a guest
Aug 28th, 2018
347
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define debug(s) cout<< #s <<" = "<< s <<endl
  6. #define all(v) (v).begin(), (v).end()
  7. #define mem(a,val) memset(a,val,sizeof a)
  8.  
  9. #define ll long long
  10. #define ff first
  11. #define ss second
  12. #define pb push_back
  13. #define endl '\n'
  14.  
  15. bool flag = 0;
  16. int n = 9,tot,g[11][11];
  17. bitset<9> row[11],col[11],blk[11];
  18. vector<pair<int,int> > v;
  19.  
  20. int block[][9] = {
  21.   { 0, 0, 0, 1, 1, 1, 2, 2, 2 },
  22.   { 0, 0, 0, 1, 1, 1, 2, 2, 2 },
  23.   { 0, 0, 0, 1, 1, 1, 2, 2, 2 },
  24.   { 3, 3, 3, 4, 4, 4, 5, 5, 5 },
  25.   { 3, 3, 3, 4, 4, 4, 5, 5, 5 },
  26.   { 3, 3, 3, 4, 4, 4, 5, 5, 5 },
  27.   { 6, 6, 6, 7, 7, 7, 8, 8, 8 },
  28.   { 6, 6, 6, 7, 7, 7, 8, 8, 8 },
  29.   { 6, 6, 6, 7, 7, 7, 8, 8, 8 } };
  30.  
  31. bool check(int x, int y, int num)
  32. {
  33.   int b = block[x][y],l = num-1;
  34.   if(row[x][l] or col[y][l] or blk[b][l]) return false;
  35.   g[x][y] = num;
  36.   row[x][l] = col[y][l] = blk[b][l] = true;
  37.   return true;
  38. }
  39.  
  40. void backtrack(int idx)
  41. {
  42.   if(flag) return;
  43.   if(idx == tot){
  44.     flag = 1;
  45.     for(int i = 0; i < n; ++i){
  46.       for(int j = 0; j < n; ++j){
  47.         cout << g[i][j];
  48.       }
  49.       cout << endl;
  50.     }
  51.     return;
  52.   }
  53.   int x = v[idx].ff;
  54.   int y = v[idx].ss;
  55.   for(int i = 1; i <= 9; ++i){
  56.     if(check(x,y,i)){
  57.       backtrack(idx+1);
  58.       if(flag) return;
  59.       g[x][y] = 0;
  60.       int l = i-1;
  61.       int b = block[x][y];
  62.       row[x][l] = col[y][l] = blk[b][l] = false;
  63.     }
  64.   }
  65. }
  66.  
  67. int main()
  68. {
  69.   ios_base::sync_with_stdio(false);cin.tie(NULL);
  70.   #ifndef ONLINE_JUDGE
  71.     freopen("in", "r", stdin);
  72.     freopen("out","w",stdout);
  73.   #endif
  74.   int t;
  75.   cin >> t;
  76.   for(int cs = 1; cs <= t; ++cs){
  77.     flag = 0;
  78.     mem(g,0);
  79.     mem(row,0);
  80.     mem(col,0);
  81.     mem(blk,0);
  82.     for(int i = 0; i < n; ++i){
  83.       for(int j = 0; j < n; ++j){
  84.         char c;
  85.         cin >> c;
  86.         if(c == '.') v.pb({i,j});
  87.         else{
  88.           g[i][j] = (c-'0');
  89.           row[i][g[i][j]-1] = col[j][g[i][j]-1] = blk[block[i][j]][g[i][j]-1] = true;
  90.         }
  91.       }
  92.     }
  93.     tot = v.size();
  94.     cout << "Case " << cs << ":" << endl;
  95.     backtrack(0);
  96.     v.clear();
  97.   }
  98. }
Add Comment
Please, Sign In to add comment