Skip to content

Commit ae2bcb4

Browse files
authored
Create main.cpp
1 parent 195d46d commit ae2bcb4

File tree

1 file changed

+39
-0
lines changed
  • 22 - Backtracking Algorithm Based Problems/03 - Sudoku Solver

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public:
3+
bool isSafe(int row, int col, vector<vector<char>>& board, int value){
4+
char ch = value + '0';
5+
6+
for(int i = 0; i < board[0].size(); i++){
7+
if(board[row][i] == ch) return false;
8+
if(board[i][col] == ch) return false;
9+
if(board[3*(row/3) + i/3][3*(col/3) + i%3] == ch) return false;
10+
}
11+
return true;
12+
}
13+
bool solve(vector<vector<char>>& board){
14+
int n = board[0].size();
15+
16+
for(int row = 0; row < n; row++){
17+
for(int col = 0; col < n; col++){
18+
if(board[row][col] == '.'){
19+
for(int val = 1; val <= 9; val++){
20+
if(isSafe(row, col, board, val)){
21+
char ch = val + '0';
22+
board[row][col] = ch;
23+
if(solve(board)) return true;
24+
board[row][col] = '.';
25+
}
26+
27+
}
28+
29+
return false;
30+
}
31+
}
32+
}
33+
34+
return true;
35+
}
36+
void solveSudoku(vector<vector<char>>& board) {
37+
solve(board);
38+
}
39+
};

0 commit comments

Comments
 (0)