[Link] https://leetcode.com/problems/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
class Solution {
public boolean isValidSudoku(char[][] board) {
HashSet<Character> hmRow = new HashSet<>();
HashSet<Character> hmCol = new HashSet<>();
for(int i = 0, l = board.length; i < l; i++) {
hmRow.clear();
hmCol.clear();
for(int j = 0; j < l; j++) {
if(board[j][i] != '.') {
if(hmCol.contains(board[j][i])) return false;
hmCol.add(board[j][i]);
}
if(board[i][j] != '.') {
if(hmRow.contains(board[i][j])) return false;
hmRow.add(board[i][j]);
}
}
}
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
if(!checkBox(board, 3 * i, 3 * j, 3 * i + 3, 3 * j + 3)) return false;
return true;
}
boolean checkBox(char[][] b, int sI, int sJ, int eI, int eJ) {
HashSet<Character> hs = new HashSet<>();
for(int i = sI; i < eI; i++) {
for(int j = sJ; j < eJ; j++) {
if(b[i][j] == '.') continue;
if(hs.contains(b[i][j])) return false;
hs.add(b[i][j]);
}
}
return true;
}
}