File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
22 - Backtracking Algorithm Based Problems/03 - Sudoku Solver Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments