Advertisement
What_Ever

Untitled

Feb 3rd, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4. int board[9][9];
  5. bool check(int key,int row,int col)
  6. {
  7.     int Srow = (row/3)*3,Scol = (col/3)*3;
  8.     for(int i = Srow ; i < (Srow+3) ;i++)
  9.         for(int j = Scol;j<(Scol+3);j++)
  10.             if(board[i][j] == key)return false;
  11.     for(int i = 0 ; i < 9 ; i++)
  12.         if(board[row][i] == key)return false;
  13.     for(int i = 0 ; i < 9 ;i++)
  14.         if(board[i][col] == key)return false;
  15.     return true;
  16. }
  17. void backtrack(int x,int y)
  18. {
  19.     if(x == 9 && y == 8)
  20.     {
  21.         for(int i = 0 ; i < 9 ; i++)
  22.         {
  23.             for(int j = 0 ; j < 9 ; j++)
  24.                 cout << board[i][j] << " ";
  25.             cout << endl;
  26.         }
  27.         return;
  28.     }
  29.     if(x == 9)
  30.     {
  31.         backtrack(0,y+1);
  32.         return;
  33.     }
  34.     for(int i = 1 ; i <= 9 ; i++)
  35.     {
  36.         if(board[x][y] == 0)
  37.             if(check(i,x,y))
  38.             {
  39.                 board[x][y] = i;
  40.                 backtrack(x+1,y);
  41.                 board[x][y] = 0;
  42.             }
  43.     }
  44. }
  45. int main()
  46. {
  47.     for(int i = 0 ; i < 9 ; i++)
  48.         for(int j = 0 ; j < 9 ; j++)
  49.             cin >> board[i][j];
  50.     backtrack(0,0);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement