forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0036-valid-sudoku.java
71 lines (60 loc) · 1.82 KB
/
0036-valid-sudoku.java
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
71
class Solution {
public boolean isValidSudoku(char[][] board) {
int rows = board.length;
int cols = board[0].length;
Set<Character> rowSet = null;
Set<Character> colSet = null;
//check for rows
for (int i = 0; i < rows; i++) {
rowSet = new HashSet<>();
for (int j = 0; j < cols; j++) {
if (board[i][j] == '.') {
continue;
}
if (rowSet.contains(board[i][j])) {
return false;
}
rowSet.add(board[i][j]);
}
}
//check for cols
for (int i = 0; i < cols; i++) {
colSet = new HashSet<>();
for (int j = 0; j < rows; j++) {
if (board[j][i] == '.') {
continue;
}
if (colSet.contains(board[j][i])) {
return false;
}
colSet.add(board[j][i]);
}
}
//block
for (int i = 0; i < rows; i = i + 3) {
for (int j = 0; j < cols; j = j + 3) {
if (!checkBlock(i, j, board)) {
return false;
}
}
}
return true;
}
public boolean checkBlock(int idxI, int idxJ, char[][] board) {
Set<Character> blockSet = new HashSet<>();
int rows = idxI + 3;
int cols = idxJ + 3;
for (int i = idxI; i < rows; i++) {
for (int j = idxJ; j < cols; j++) {
if (board[i][j] == '.') {
continue;
}
if (blockSet.contains(board[i][j])) {
return false;
}
blockSet.add(board[i][j]);
}
}
return true;
}
}