Leetcode 36. Valid Sudoku (Easy) (cpp)
Tag: Hash Table
Difficulty: Easy
/*
36. Valid Sudoku (Easy)
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
*/
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
for (int i = 0; i < 9; i++) {
unordered_map<char, bool> mapping1;
unordered_map<char, bool> mapping2;
unordered_map<char, bool> mapping3;
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
if (mapping1[board[i][j]] == true) {
return false;
} else {
mapping1[board[i][j]] = true;
}
}
if (board[j][i] != '.') {
if (mapping2[board[j][i]] == true) {
return false;
} else {
mapping2[board[j][i]] = true;
}
}
if (board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3] != '.') {
if (mapping3[board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]] == true) {
return false;
} else {
mapping3[board[i / 3 * 3 + j / 3][i % 3 * 3 + j % 3]] = true;
}
}
}
}
return true;
}
};
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int mapping1[9][9] = {0};
int mapping2[9][9] = {0};
int mapping3[9][9] = {0};
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
int num = board[i][j] - '0' - 1, k = i / 3 * 3 + j / 3;
if (mapping1[i][num] || mapping2[j][num] || mapping3[k][num]) {
return false;
}
mapping1[i][num] = mapping2[j][num] = mapping3[k][num] = 1;
}
}
}
return true;
}
};