LeetCode: Valid Sudoku

LeetCode: Valid Sudoku

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
public class ValidSudoku {
public boolean isValidSudoku(char[][] board) {
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < 9; i++) {
set.clear();
for (int j = 0; j < 9; j++) {
char c = board[i][j];
if (c != '.') {
if (set.contains(c)) {
return false;
} else {
set.add(c);
}
}
}
}
for (int i = 0; i < 9; i++) {
set.clear();
for (int j = 0; j < 9; j++) {
char c = board[j][i];
if (c != '.') {
if (set.contains(c)) {
return false;
} else {
set.add(c);
}
}
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int r = 3 * i;
int c = 3 * j;
set.clear();
for (int x = r; x < r + 3; x++) {
for (int y = c; y < c + 3; y++) {
char z = board[x][y];
if (z != '.') {
if (set.contains(z)) {
return false;
} else {
set.add(z);
}
}
}
}
}
}
return true;
}
}