forked from Nimesh-Srivastava/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0036.cpp
More file actions
55 lines (40 loc) · 1.43 KB
/
0036.cpp
File metadata and controls
55 lines (40 loc) · 1.43 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
//Solution using 3 hash maps
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int r = board.size();
int c = board[0].size();
unordered_map<char, int> row[9];
unordered_map<char, int> col[9];
unordered_map<char, int> box[9];
for(int i=0; i<r; i++){
for(int j=0; j<c; j++){
char ch = board[i][j];
if(ch != '.' &&
(row[i][ch]++ > 0 || col[j][ch]++ > 0 || box[(i/3)*3 + j/3][ch]++ > 0))
return false;
}
}
return true;
}
};
//Solution using three 2D arrays
//Faster, better solution
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int row[9][9] = {0}, col[9][9] = {0}, box[9][9] = {0};
for(int i=0; i<board.size(); i++){
for(int j=0; j<board[0].size(); j++){
if(board[i][j] != '.'){
int val = board[i][j] - '0' - 1;
int k = (i/3)*3 + (j/3);
if(row[i][val] || col[j][val] || box[k][val])
return false;
row[i][val] = col[j][val] = box[k][val] = 1;
}
}
}
return true;
}
};