Advertisement
Guest User

SudokuBacktracking

a guest
Feb 22nd, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int grid[100][100];
  5.  
  6. struct POINT
  7. {
  8.     int x, y;
  9. };
  10.  
  11. void SolveSudoku(int n, int k)
  12. {
  13.     if (k == n * n)
  14.         printGrid();
  15.     else
  16.     {
  17.         POINT g;
  18.         g = FindUnassignedLocation(n);
  19.         for (int num = 1; num <= n; num++)
  20.         {
  21.             if (isSafe(n, row, col, num))
  22.             {
  23.                 grid[row][col] = num;
  24.  
  25.                 SolveSudoku(n, k + 1);
  26.  
  27.                 grid[row][col] = 0;
  28.             }
  29.         }
  30.     }
  31. }
  32.  
  33. POINT FindUnassignedLocation(int n)
  34. {
  35.     int row, col;
  36.     POINT g;
  37.     for (row = 0; row < n; row++)
  38.         for (col = 0; col < n; col++)
  39.             if (grid[row][col] == 0)
  40.             {
  41.                 g.x = row;
  42.                 g.y = col;
  43.                 return g;
  44.             }
  45.     return g;
  46.  
  47. }
  48.  
  49. bool UsedInRow(int n, int row, int num)
  50. {
  51.     for (int col = 0; col < n; col++)
  52.         if (grid[row][col] == num)
  53.             return true;
  54.     return false;
  55. }
  56.  
  57. bool UsedInCol(int n, int col, int num)
  58. {
  59.     for (int row = 0; row < n; row++)
  60.         if (grid[row][col] == num)
  61.             return true;
  62.     return false;
  63. }
  64.  
  65. bool isSafe(int n, int row,
  66.                 int col, int num)
  67. {
  68.     return !UsedInCol(n, col, num) && !UsedInRow(n, row, num)&&
  69.             grid[row][col] == 0;
  70. }
  71.  
  72. void printGrid()
  73. {
  74.     int row, col;
  75.     for (int row = 0; row < n; row++)
  76.     {
  77.     for (int col = 0; col < n; col++)
  78.             cout << grid[row][col] << " ";
  79.         cout << endl;
  80.     }
  81. }
  82.  
  83. int main()
  84. {
  85.     SolveSudoku(n, 0);
  86.  
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement