Advertisement
Fastrail08

SolveSudoko

May 2nd, 2025
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.97 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // to check if the row already has the number
  5. bool checkRow(int r, int k, vector<vector<int> > &v){
  6.     for(int i : v[r]){
  7.         if(i == k){
  8.             return false;
  9.         }
  10.     }
  11.     return true;
  12. }
  13.  
  14. // to check if the column already has the number
  15. bool checkColumn(int c, int k, vector<vector<int> > &v){
  16.     for(int i = 0; i < v.size(); i++){
  17.         if(v[i][c] == k){
  18.             return false;
  19.         }
  20.     }
  21.     return true;
  22. }
  23.  
  24. // to check if the submatrix already has the number
  25. bool checkSubmatrix(int r, int c, int k, vector<vector<int> > &v){
  26.     // calculate column range
  27.     int colInterval = ceil((c + 1) / 3.0);
  28.     int rowInterval = ceil((r + 1) / 3.0);
  29.    
  30.     for(int i = 3 * (rowInterval - 1); i < 3 * rowInterval; i++){
  31.         for(int j = 3 * (colInterval - 1); j < 3 * colInterval; j++){
  32.             if(v[i][j] == k){
  33.                 return false;
  34.             }
  35.         }
  36.     }
  37.     return true;
  38. }
  39.  
  40.  
  41. // main solve function
  42. void solveSudoko(int r, int c, vector<vector<int> > &v){
  43.     if(c >= 9){
  44.         r = r + 1;
  45.         c = 0;
  46.     }
  47.     if(r >= 9){
  48.         for(int i = 0; i < 9; i++){
  49.             cout << '\n';
  50.             for(int j = 0; j < 9; j++){
  51.                 cout << v[i][j] << ' ';
  52.             }
  53.         }
  54.         cout << '\n' << '\n';
  55.         return;
  56.     }
  57.     if(v[r][c] == 0){
  58.         for(int k = 1; k < 10; k++){
  59.             bool isSafe = checkRow(r, k, v) && checkColumn(c, k, v) && checkSubmatrix(r, c, k, v);
  60.             if(isSafe){
  61.              v[r][c] = k;
  62.              solveSudoko(r, c + 1, v);
  63.              v[r][c] = pas0;
  64.             }
  65.         }
  66.        
  67.     }
  68.     else{
  69.         solveSudoko(r, c + 1, v);
  70.     }
  71. }
  72.  
  73. int main() {
  74.     // your code goes here
  75.     vector<vector<int> > v(9, vector<int>(9, 0));
  76.     for(int i = 0; i < 9; i++){
  77.         for(int j = 0; j < 9; j++){
  78.             cin >> v[i][j];
  79.         }
  80.     }
  81.  
  82.     solveSudoko(0, 0, v);
  83. }
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement