mirror of
https://github.com/allankoechke/neetcode-submissions.git
synced 2026-11-29 09:18:38 +00:00
Add: valid-sudoku - submission-1
This commit is contained in:
57
Data Structures & Algorithms/valid-sudoku/submission-1.cpp
Normal file
57
Data Structures & Algorithms/valid-sudoku/submission-1.cpp
Normal file
@@ -0,0 +1,57 @@
|
||||
class Solution {
|
||||
bool hasDuplicate(const std::vector<char> block) {
|
||||
std::unordered_set<char> seen;
|
||||
for(const char c: block) {
|
||||
// Ignore empty cells (denoted by '.')
|
||||
if(c == '.') continue;
|
||||
|
||||
auto [_, added] = seen.insert(c);
|
||||
if(!added) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<char> getGrid(vector<vector<char>>& board, const int row, const int col) {
|
||||
std::vector<char> result;
|
||||
|
||||
// Get actual row and col by * 3
|
||||
auto _row = row * 3;
|
||||
auto _col = col * 3;
|
||||
|
||||
result.insert(result.end(), board[_row].begin() + _col, board[_row].begin() + _col + 3);
|
||||
result.insert(result.end(), board[_row+1].begin() + _col, board[_row+1].begin() + _col + 3);
|
||||
result.insert(result.end(), board[_row+2].begin() + _col, board[_row+2].begin() + _col + 3);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public:
|
||||
bool isValidSudoku(vector<vector<char>>& board) {
|
||||
// Check rows for duplicates
|
||||
for(const auto& row: board) {
|
||||
if(hasDuplicate(row)) return false;
|
||||
}
|
||||
|
||||
// Check column for duplicates
|
||||
for(int col=0; col<9; col++) {
|
||||
std::vector<char> col_vec;
|
||||
|
||||
for(int row=0; row<9; row++) {
|
||||
col_vec.push_back(board[row][col]);
|
||||
}
|
||||
|
||||
if(hasDuplicate(col_vec)) return false;
|
||||
}
|
||||
|
||||
// Check for 3x3 grid validity
|
||||
for(int row = 0; row<3; row++) {
|
||||
for(int col = 0; col<3; col++) {
|
||||
auto grid = getGrid(board, row, col);
|
||||
if(hasDuplicate(grid)) return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user