leetcode 36 c++
C++ Solution for LeetCode Problem 36: Valid Sudoku
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
vector<unordered_set<int>> rows(9), cols(9), boxes(9);
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
char num = board[i][j];
if (num != '.') {
int n = num - '0';
int box_index = (i / 3) * 3 + j / 3;
if (rows[i].count(n) || cols[j].count(n) || boxes[box_index].count(n)) {
return false;
}
rows[i].insert(n);
cols[j].insert(n);
boxes[box_index].insert(n);
}
}
}
return true;
}
};
Explanation:
- Create three vectors of unordered sets to keep track of the numbers in each row, column, and box.
- Loop through each cell of the Sudoku board.
- For each cell, check if the number is a digit (not a dot).
- Calculate the index of the box the cell belongs to.
- Check if the number already exists in the current row, column, or box. If it does, return false.
- If the number doesn't exist in any of the sets, insert it into the sets.
- If the loop completes without finding any conflicts, return true.