Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- int board[9][9];
- bool check(int key,int row,int col)
- {
- int Srow = (row/3)*3,Scol = (col/3)*3;
- for(int i = Srow ; i < (Srow+3) ;i++)
- for(int j = Scol;j<(Scol+3);j++)
- if(board[i][j] == key)return false;
- for(int i = 0 ; i < 9 ; i++)
- if(board[row][i] == key)return false;
- for(int i = 0 ; i < 9 ;i++)
- if(board[i][col] == key)return false;
- return true;
- }
- void backtrack(int x,int y)
- {
- if(x == 9 && y == 8)
- {
- for(int i = 0 ; i < 9 ; i++)
- {
- for(int j = 0 ; j < 9 ; j++)
- cout << board[i][j] << " ";
- cout << endl;
- }
- return;
- }
- if(x == 9)
- {
- backtrack(0,y+1);
- return;
- }
- for(int i = 1 ; i <= 9 ; i++)
- {
- if(board[x][y] == 0)
- if(check(i,x,y))
- {
- board[x][y] = i;
- backtrack(x+1,y);
- board[x][y] = 0;
- }
- }
- }
- int main()
- {
- for(int i = 0 ; i < 9 ; i++)
- for(int j = 0 ; j < 9 ; j++)
- cin >> board[i][j];
- backtrack(0,0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement