-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_SudokuProblem.cpp
More file actions
53 lines (43 loc) · 1.82 KB
/
02_SudokuProblem.cpp
File metadata and controls
53 lines (43 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Approach:
// 1. traverse the matrix and find the empty place.
// 2. once we find the empty place than we tried all the numbers from 1 to 9 and check that it is a valid number or not by checking the rules.
// 3. and we find the correct number for that place than we find for the second empty place in 9 X 9 matrix.
// 4. for second empty place we repeat the same process and if we doesn't get any number, so we return false.
// 5. after getting the false from solve(board) function we make all the places empty that we have filled . than try for other member for first empty place.
// 6. and after all recursive calls we got true, than we have to stop over there only and no need to search for other solutions.
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
solve(board);
}
bool solve(vector<vector<char>>& board){
for(int i=0; i<board.size(); i++){
for(int j=0; j<board[0].size(); j++){
if(board[i][j] == '.'){
for(char c='1'; c<='9'; c++){
if(isValid(board, i, j, c)){
board[i][j] = c;
if(solve(board) == true)
return true;
else
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
bool isValid(vector<vector<char>>& board, int row, int col, char c){
for(int i=0; i<9; i++){
if(board[i][col] == c)
return false;
if(board[row][i] == c)
return false;
if(board[3 * (row/3) + i/3][3 * (col/3) + i%3] == c)
return false;
}
return true;
}
};