-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0033_ValidSudoku.cpp
More file actions
70 lines (64 loc) · 2.67 KB
/
Copy path0033_ValidSudoku.cpp
File metadata and controls
70 lines (64 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <fmt/ranges.h>
#include <ranges>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution
{
public:
bool isValidSudoku(vector<vector<char>> &board)
{
std::unordered_set<char> rowHash, colHash[9], gridHash[9];
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[i].size(); j++) {
if (const char entry = board[i][j]; entry != '.') {
const int quadrant = i / 3 * 3 + j / 3;
if (rowHash.contains(entry) or colHash[j].contains(entry)
or gridHash[quadrant].contains(entry))
return false;
rowHash.insert(entry);
colHash[j].insert(entry);
gridHash[quadrant].insert(entry);
}
}
rowHash.clear();
}
return true;
}
void printBoard(vector<vector<char>> &board)
{
for (auto row : board) {
for (auto cell : row) {
fmt::print("{} ", cell);
}
fmt::print("\n");
}
}
};
int main()
{
Solution sol;
// test cases
vector<vector<char>> test1{{'5', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}};
vector<vector<char>> test2{{'8', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}};
for (auto test : {test1, test2}) {
sol.printBoard(test);
fmt::print("result: {}\n", sol.isValidSudoku(test));
}
}