Advertisement
Guest User

Untitled

a guest
Feb 21st, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <array>
  5.  
  6.  
  7. void printMatrix(int grid[9][9]);
  8. bool possible(int y, int x, int n, int grid[9][9]);
  9. void solve(int grid[9][9]);
  10.  
  11. int main() {
  12.     int sudoku[9][9] = {
  13.         { 5, 3, 0, 0, 7, 0, 0, 0, 0},
  14.         { 6, 0, 0, 1, 9, 5, 0, 0, 0},
  15.         { 0, 9, 8, 0, 0, 0, 0, 6, 0},
  16.         { 8, 0, 0, 0, 6, 0, 0, 0, 3},
  17.         { 4, 0, 0, 8, 0, 3, 0, 0, 1},
  18.         { 7, 0, 0, 0, 2, 0, 0, 0, 6},
  19.         { 0, 6, 0, 0, 0, 0, 2, 8, 0},
  20.         { 0, 0, 0, 4, 1, 9, 0, 0, 5},
  21.         { 0, 0, 0, 0, 8, 0, 0, 7, 9},
  22.     };
  23.  
  24.     printMatrix(sudoku);
  25.     std::cout << std::endl;
  26.     solve(sudoku);
  27. }
  28.  
  29. void solve(int grid[9][9]) {
  30.     for (int x = 0; x < 9; ++x) {
  31.         for (int y = 0; y < 9; ++y) {
  32.             if (grid[x][y] == 0) {
  33.  
  34.                 for (int n = 1; n < 10; ++n) {
  35.                     if (possible(y, x, n, grid)) {
  36.                         grid[x][y] = n;
  37.                         solve(grid);
  38.                         grid[x][y] = 0;
  39.                     }
  40.                 }
  41.  
  42.                 return;
  43.             }
  44.         }
  45.     }
  46.  
  47.     printMatrix(grid);
  48. }
  49.  
  50. bool possible(int y, int x, int n, int grid[9][9]) {
  51.     for (int i = 0; i < 9; ++i) { if (grid[i][y] == n) { return false; } }
  52.     for (int i = 0; i < 9; ++i) { if (grid[x][i] == n) { return false; } }
  53.  
  54.     int x0 = (x / 3) * 3;
  55.     int y0 = (y / 3) * 3;
  56.     for (int i = 0; i < 3; ++i) {
  57.         for (int j = 0; j < 3; ++j) {
  58.             if (grid[x0 + i][y0 + j] == n) {
  59.                 return false;
  60.             }
  61.         }
  62.     }
  63.  
  64.     return true;
  65. }
  66.  
  67. void printMatrix(int grid[9][9]) {
  68.     for (int i = 0; i < 9; ++i) {
  69.         std::stringstream ss;
  70.         for (int j = 0; j < 9; ++j) {
  71.             ss << grid[i][j] << " ";
  72.         }
  73.         std::cout << ss.str() << std::endl;
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement