Skip to content

Commit 6732d76

Browse files
authored
Updating C++ solution for 36.Valid Sudoku
Updated the code, using boolean matrices to account for seen values in rows, cols, and sub boxes. More readable code.
1 parent 7b13263 commit 6732d76

File tree

1 file changed

+21
-49
lines changed

1 file changed

+21
-49
lines changed
Lines changed: 21 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,38 @@
11
/*
22
Determine if a 9x9 Sudoku board is valid (no repeats)
33
4-
Hash set to store seen values, check rows, cols, blocks
4+
Boolean matrices to store seen values. Check rows, cols, 3x3 sub-boxes
55
6-
Time: O(n^2)
7-
Space: O(n^2)
6+
Time: O(cnt^2)
7+
Space: O(cnt^2)
88
*/
99

1010
class Solution {
1111
public:
1212
bool isValidSudoku(vector<vector<char>>& board) {
13-
unordered_set<char> s;
13+
const int cnt = 9;
14+
bool row[cnt][cnt] = {false};
15+
bool col[cnt][cnt] = {false};
16+
bool sub[cnt][cnt] = {false};
1417

15-
for (int i = 0; i < 9; i++) {
16-
for (int j = 0; j < 9; j++) {
17-
if (board[i][j] == '.') {
18-
continue;
19-
}
20-
auto it = s.find(board[i][j]);
21-
if (it != s.end()) {
22-
return false;
23-
} else {
24-
s.insert(board[i][j]);
25-
}
26-
}
27-
s.clear();
28-
}
29-
30-
for (int i = 0; i < 9; i++) {
31-
for (int j = 0; j < 9; j++) {
32-
if (board[j][i] == '.') {
33-
continue;
34-
}
35-
auto it = s.find(board[j][i]);
36-
if (it != s.end()) {
18+
for(int r = 0; r < cnt; ++r){
19+
for(int c = 0; c < cnt; ++c){
20+
if(board[r][c] == '.')
21+
continue; // if not number pass
22+
23+
int idx = board[r][c] - '0' - 1; //char to num idx
24+
int area = (r/3) * 3 + (c/3);
25+
26+
//if number already exists
27+
if(row[r][idx] || col[c][idx] || sub[area][idx]){
3728
return false;
38-
} else {
39-
s.insert(board[j][i]);
40-
}
41-
}
42-
s.clear();
43-
}
44-
45-
for (int iCount = 0; iCount < 9; iCount += 3) {
46-
for (int jCount = 0; jCount < 9; jCount += 3) {
47-
for (int i = iCount; i < iCount + 3; i++) {
48-
for (int j = jCount; j < jCount + 3; j++) {
49-
if (board[i][j] == '.') {
50-
continue;
51-
}
52-
auto it = s.find(board[i][j]);
53-
if (it != s.end()) {
54-
return false;
55-
} else {
56-
s.insert(board[i][j]);
57-
}
58-
}
5929
}
60-
s.clear();
30+
31+
row[r][idx] = true;
32+
col[c][idx] = true;
33+
sub[area][idx] = true;
6134
}
6235
}
63-
6436
return true;
6537
}
6638
};

0 commit comments

Comments
 (0)