forked from timoncui/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValid_Sudoku.cpp
More file actions
43 lines (37 loc) · 1011 Bytes
/
Valid_Sudoku.cpp
File metadata and controls
43 lines (37 loc) · 1011 Bytes
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
/*
Author: Timon Cui, [email protected]
Title: Valid Sudoku
Description:
Difficulty rating:
Notes: It's important to make the function distinct() efficient.
Further optimization is possible by returning false once res becomes false.
*/
class Solution {
public:
bool distinct(const vector<char>& v) {
vector<int> counter(9, 0);
for (int i = 0; i < v.size(); ++i) {
if (v[i] != '.') {
int index = v[i] - '1';
if (counter[index]++ > 0) return false;
}
}
return true;
}
bool isValidSudoku(vector<vector<char> > &board) {
bool res = true;
vector<vector<char> > columns(9), squares(9);
for (int i = 0; i < 9; ++i) {
res &= distinct(board[i]);
for (int j = 0; j < 9; ++j) {
columns[j].push_back(board[i][j]);
squares[i / 3 + j / 3 * 3].push_back(board[i][j]);
}
}
for (int i = 0; i < 9; ++i) {
res &= distinct(columns[i]);
res &= distinct(squares[i]);
}
return res;
}
};