Dmaxiya

P1784 数独 参考代码

Feb 6th, 2026
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define endl '\n'
  5.  
  6. typedef long long LL;
  7. const int maxn = 10 + 100;
  8. int n;
  9. bool flag;
  10. int num[maxn][maxn];
  11. bool visRow[10][10], visCol[10][10], visBlock[10][10];
  12.  
  13. inline int calBlockIdx(int x, int y) {
  14.     return x / 3 * 3 + y / 3;
  15. }
  16.  
  17. void output() {
  18.     for (int i = 0; i < n; ++i) {
  19.         for (int j = 0; j < n; ++j) {
  20.             cout << num[i][j] << " ";
  21.         }
  22.         cout << endl;
  23.     }
  24. }
  25.  
  26. void fillin(int r, int c, int x) {
  27.     num[r][c] = x;
  28.     visRow[r][x] = true;
  29.     visCol[c][x] = true;
  30.     visBlock[calBlockIdx(r, c)][x] = true;
  31. }
  32.  
  33. void rm(int r, int c) {
  34.     int x = num[r][c];
  35.     visRow[r][x] = false;
  36.     visCol[c][x] = false;
  37.     visBlock[calBlockIdx(r, c)][x] = false;
  38.     num[r][c] = 0;
  39. }
  40.  
  41. bool judge(int r, int c, int x) {
  42.     if (visRow[r][x]) {
  43.         return false;
  44.     }
  45.     if (visCol[c][x]) {
  46.         return false;
  47.     }
  48.     int block = calBlockIdx(r, c);
  49.     return !visBlock[block][x];
  50. }
  51.  
  52. void dfs(int depth) {
  53.     if (depth == n * n) {
  54.         flag = true;
  55.         output();
  56.         return ;
  57.     }
  58.     int x = depth / 9;
  59.     int y = depth % 9;
  60.     if (num[x][y] != 0) {
  61.         dfs(depth + 1);
  62.         return ;
  63.     }
  64.     for (int i = 1; i <= n; ++i) {
  65.         if (judge(x, y, i)) {
  66.             fillin(x, y, i);
  67.             dfs(depth + 1);
  68.             if (flag) {
  69.                 return ;
  70.             }
  71.             rm(x, y);
  72.         }
  73.     }
  74. }
  75.  
  76. int main() {
  77. #ifdef ExRoc
  78.     freopen("test.txt", "r", stdin);
  79. #endif // ExRoc
  80.     ios::sync_with_stdio(false);
  81.  
  82.     n = 9;
  83.     for (int i = 0; i < n; ++i) {
  84.         for (int j = 0; j < n; ++j) {
  85.             int x;
  86.             cin >> x;
  87.             fillin(i, j, x);
  88.         }
  89.     }
  90.     dfs(0);
  91.  
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment