-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path37_Sudoku_Solver.cpp
More file actions
59 lines (54 loc) · 1.42 KB
/
37_Sudoku_Solver.cpp
File metadata and controls
59 lines (54 loc) · 1.42 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
54
55
56
57
58
59
class Solution {
public:
bool issafe(vector<vector<char>>& board, int row, int col,int digit){
//horizontal
for (int j =0 ;j<9;j++){
if(board[row][j] == digit){
return false;
}
}
//vertical
for (int i =0;i<9;i++){
if (board[i][col]==digit){
return false;
}
}
//grid
int srow = (row/3)*3;
int scol = (col/3)*3;
for(int i=srow;i<=srow+2;i++){
for(int j=scol;j<=scol+2;j++){
if(board[i][j]==digit){
return false;
}
}
}
return true;
}
bool helper(vector<vector<char>>& board, int row, int col){
if (row ==9){
return true;
}
int nextrow = row, nextcol = col +1;
if(nextcol==9){
nextrow = row+1;
nextcol=0;
}
if(board[row][col]!='.'){
return helper(board,nextrow,nextcol);
}
for(char digit='1';digit<='9';digit++){
if(issafe(board,row,col,digit)){
board[row][col] = digit;
if(helper(board,nextrow,nextcol)){
return true;
}
board[row][col]='.';
}
}
return false;
}
void solveSudoku(vector<vector<char>>& board) {
helper(board,0,0);
}
};