bhupixb

Sudoko Solver

Jan 23rd, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3.  
  4. const int N = 12;
  5. int dp[N][N], maskCol[N], maskRow[N];
  6. int refMask[N][N], matMask[N];
  7. int cnt = 0;
  8.  
  9. bool check() {
  10. for (int i = 1; i <= 9; i += 3) {
  11. for (int j = 1; j <= 9; j += 3) {
  12. int maskCol = 0;
  13. for (int r = i; r < i + 3; ++r) {
  14. for (int c = j; c < j + 3; ++c) {
  15. if (!dp[r][c]) return 0;
  16. if (maskCol & (1<<dp[r][c])) return 0;
  17. maskCol |= (1<<dp[r][c]);
  18. }
  19. }
  20. }
  21. }
  22. for (int i = 1; i <= 9; ++i) {
  23. int maskCol = 0;
  24. for (int j = 1; j <= 9; ++j) {
  25. if (maskCol & (1<<dp[i][j])) return 0;
  26. maskCol |= (1<<dp[i][j]);
  27. }
  28. }
  29. for (int i = 1; i <= 9; ++i) {
  30. int maskCol = 0;
  31. for (int j = 1; j <= 9; ++j) {
  32. if (maskCol & (1<<dp[j][i])) return 0;
  33. maskCol |= (1<<dp[j][i]);
  34. }
  35. }
  36. // Uncomment to print solution
  37. // for (int i = 1; i <= 9; i += 1) {
  38. // for (int j = 1; j <= 9; j += 1) {
  39. // cout << dp[i][j] << " \n"[j==9];
  40. // }
  41. // }
  42. // exit(0);
  43. return true;
  44. }
  45. int ans = 0;
  46. void go(int row, int col) {
  47. ++cnt;
  48. if (row == 1 and col == 10 && check()) {
  49. return;
  50. }
  51. if (cnt > 5e5) {
  52. cout << "Seems like infinite loop\n";
  53. exit(0);
  54. }
  55. if (row > 9 or col > 9) return;
  56. if (dp[row][col]) {
  57. if (row == 9) go(1,col+1);
  58. else go(row+1,col);
  59. }
  60. else {
  61. for (int i = 1; i <= 9; ++i) {
  62. if (!(maskCol[col] & (1<<i)) && !(maskRow[row] & (1<<i))) {
  63. if (matMask[refMask[row][col]] & (1<<i)) continue;
  64. maskCol[col] += (1<<i);
  65. maskRow[row] += (1<<i);
  66. matMask[refMask[row][col]] += 1<<i;
  67. dp[row][col] = i;
  68. if (row == 9) go(1,col+1);
  69. else go(row+1,col);
  70. maskCol[col] -= (1<<i);
  71. maskRow[row] -= (1<<i);
  72. matMask[refMask[row][col]] -= 1<<i;
  73. dp[row][col] = 0;
  74. }
  75. }
  76. }
  77. }
  78.  
  79. int main() {
  80. int ok = 1;
  81. for (int i = 1; i <= 9; i += 3) {
  82. for (int j = 1; j <= 9; j += 3) {
  83. for (int r = i; r < i + 3; ++r) {
  84. for (int c = j; c < j + 3; ++c) {
  85. refMask[r][c] = ok;
  86. }
  87. }
  88. ++ok;
  89. }
  90. }
  91. // go(1,1);
  92.  
  93. return 0;
  94. }
Add Comment
Please, Sign In to add comment