Advertisement
mickypinata

SMMR-T142: Sudoku

Mar 26th, 2020
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. char head[15];
  6. bool lock;
  7. int table[10][10];
  8.  
  9. void PrintTable(){
  10.     printf("%s\n", head);
  11.     for(int i = 0; i < 9; ++i){
  12.         for(int j = 0; j < 9; ++j){
  13.             cout << table[i][j] << " ";
  14.         }
  15.         cout << "\n";
  16.     }
  17.     return;
  18. }
  19.  
  20. bool ValidNumber(int r, int c, int x){
  21.     for(int i = 0; i < 9; ++i){
  22.         if(table[i][c] == x|| table[r][i] == x){
  23.             return false;
  24.         }
  25.     }
  26.     for(int i = r - (r % 3); i < r - (r % 3) + 3; ++i){
  27.         for(int j = c - (c % 3); j < c - (c % 3) + 3; ++j){
  28.             if(table[i][j] == x){
  29.                 return false;
  30.             }
  31.         }
  32.     }
  33.     return true;
  34. }
  35.  
  36. void Sudoku(int row, int col){
  37.     if(row == 9 && col == 0){
  38.         if(!lock){
  39.             PrintTable();
  40.             lock = true;
  41.         }
  42.         return;
  43.     } else if(table[row][col] != 0){
  44.         if(col == 8 && !lock){
  45.             Sudoku(row + 1, 0);
  46.         } else {
  47.             Sudoku(row, col + 1);
  48.         }
  49.         return;
  50.     } else {
  51.         for(int i = 1; i <= 9; ++i){
  52.             if(ValidNumber(row, col, i) && !lock){
  53.                 table[row][col] = i;
  54.                 if(col == 8){
  55.                     Sudoku(row + 1, 0);
  56.                 } else {
  57.                     Sudoku(row, col + 1);
  58.                 }
  59.                 table[row][col] = 0;
  60.             }
  61.         }
  62.         return;
  63.     }
  64. }
  65.  
  66. int main(){
  67.  
  68.     freopen("input_sudoku.txt", "r", stdin);
  69.     freopen("output_sudoku.txt", "w", stdout);
  70.  
  71.     int x;
  72.  
  73.     for(int k = 0; k < 100; ++k){
  74.         lock = false;
  75.         scanf(" %[^\n]", head);
  76.         for(int i = 0; i < 9; ++i){
  77.             for(int j = 0; j < 9; ++j){
  78.                 scanf("%d", &x);
  79.                 table[i][j] = x;
  80.             }
  81.         }
  82.         Sudoku(0, 0);
  83.     }
  84.  
  85.     fclose(stdout);
  86.  
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement