Valid Sudoku Algorithm
The Valid Sudoku Algorithm is a technique used to check the validity of a given Sudoku puzzle, ensuring that it adheres to the basic rules of the game. These rules include having unique numbers (between 1 and 9) in each row, column, and 3x3 grid of the 9x9 puzzle board. The algorithm essentially validates that there are no repeated numbers within these groups, guaranteeing that the puzzle can be solved without any conflicts or contradictions.
To achieve this, the algorithm typically employs the use of data structures like sets, lists, or hashmaps to keep track of the elements encountered in each row, column, and grid. It iterates through the entire puzzle board, examining each cell and updating the corresponding data structures accordingly. For instance, while traversing a row, the algorithm can add each number encountered to a set or hashmap and check if the current number already exists in the set or hashmap. If a duplicate is found, it implies that the puzzle is invalid. This process is repeated for columns and 3x3 grids as well. If no duplicates are found throughout the entire board, the algorithm concludes that the given Sudoku puzzle is valid and adheres to the game's rules.
class Solution {
public:
bool isValidSudoku(vector<vector<char>> &board) {
vector<vector<bool>> rows(9, vector<bool>(9, false));
vector<vector<bool>> cols(9, vector<bool>(9, false));
vector<vector<bool>> cells(9, vector<bool>(9, false));
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
int x = board[i][j] - '1';
if (rows[i][x] || cols[j][x] || cells[(j/3)*3+i/3][x]) {
return false;
}
rows[i][x] = true;
cols[j][x] = true;
cells[(j/3)*3+i/3][x] = true;
}
}
}
return true;
}
};