Created
August 22, 2020 04:22
-
-
Save souravrax/422f6a43f301fa3ccd644712d27cdcb7 to your computer and use it in GitHub Desktop.
This is a 9x9 Sudoku Solver using Backtracking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const int N = 9; | |
class Solution { | |
bool canPlace(vector<vector<char>>& board, int i, int j, char x) { | |
// row check | |
for(int c = 0; c<9; c++) { | |
if(board[i][c] == x) { | |
return false; | |
} | |
} | |
// column check | |
for(int r=0; r<9; r++) { | |
if(board[r][j] == x) { | |
return false; | |
} | |
} | |
// box check | |
i = i / 3 * 3; | |
j = j / 3 * 3; | |
bool bStatus = true; | |
for(int r=0; r<3; r++) { | |
for(int c=0; c<3; c++) { | |
if(board[r + i][c + j] == x) { | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
char tochar(int x) { | |
return char(x + int('0')); | |
} | |
bool solve(vector<vector<char>>& board) { | |
bool found = false; | |
int i, j; | |
for(i=0; i<N; i++) { | |
for(j=0; j<N; j++) { | |
if(board[i][j] == '.') { | |
found = true; | |
break; | |
} | |
} | |
if(found) break; | |
} | |
if(!found) return true; | |
for(int x=1; x<=N; x++) { | |
if(canPlace(board, i, j, tochar(x))) { | |
board[i][j] = tochar(x); | |
if(solve(board)) return true; | |
board[i][j] = '.'; | |
} | |
} | |
return false; | |
} | |
public: | |
void solveSudoku(vector<vector<char>>& board) { | |
solve(board); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment