Description
Submission
class Solution {
public:
bool isValid(vector<vector<char>>& board, int row, int col, char val) {
for(int i = 0; i < board.size(); ++i) {
if(board[row][i] == val) return false;
if(board[i][col] == val) return false;
int r = row / 3 * 3 + i / 3;
int c = col / 3 * 3 + i % 3;
if(board[r][c] == val)
return false;
}
return true;
}
bool solve(vector<vector<char>>& board) {
for(int i = 0; i < board.size(); ++i) {
for(int j = 0; j < board.size(); ++j) {
if(board[i][j] == '.') {
for(int k = 0; k < 9; ++k) {
if(isValid(board, i, j, '1' + k)) {
board[i][j] = '1' + k;
if(solve(board)) return true;
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
void solveSudoku(vector<vector<char>>& board) {
solve(board);
}
};
References
- https://leetcode.com/problems/sudoku-solver/discuss/734304/Extremely-Simple-CPP-Solution-with-excessive-comments-and-Line-by-Line-explanation.