Skip to content

Commit da5732b

Browse files
committed
Add Sudoku Solver Problem
1 parent 114bff6 commit da5732b

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Sudoku_Solver/submission1.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution {
2+
private:
3+
bool isValid(vector<vector<char>>& board, int position, int digit){
4+
int x = position/9, y = position%9, blockX = x/3, blockY = y/3;
5+
6+
for (int i=0; i<9; i++){
7+
if (board[x][i]==digit+'0' || board[i][y]==digit+'0' || board[blockX*3+i/3][blockY*3+i%3]==digit+'0'){
8+
return false;
9+
}
10+
}
11+
12+
return true;
13+
}
14+
15+
bool solve(vector<vector<char>>& board, int position){
16+
17+
if (position == 81){
18+
return true;
19+
}
20+
21+
if (board[position/9][position%9] != '.'){
22+
return solve(board, position+1);
23+
}
24+
25+
for (int digit=1; digit<=9; digit++){
26+
if (isValid(board, position, digit)){
27+
board[position/9][position%9] = digit+'0';
28+
if (solve(board, position+1)){
29+
return true;
30+
}
31+
board[position/9][position%9] = '.';
32+
}
33+
}
34+
35+
return false;
36+
}
37+
38+
public:
39+
void solveSudoku(vector<vector<char>>& board) {
40+
int position = 0;
41+
solve(board, position);
42+
}
43+
};

0 commit comments

Comments
 (0)