-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidSudoku.java
30 lines (28 loc) · 1.17 KB
/
ValidSudoku.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
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ValidSudoku {
public boolean isValidSudoku(char[][] board) {
Map<Integer, Set<Character>> cols = new HashMap<>();
Map<Integer, Set<Character>> rows = new HashMap<>();
Map<Integer, Set<Character>> squares = new HashMap<>(); // key = (r / 3) * 3 + c / 3
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
char cell = board[r][c];
if (cell == '.') {
continue;
}
if (rows.getOrDefault(r, new HashSet<>()).contains(cell)
|| cols.getOrDefault(c, new HashSet<>()).contains(cell)
|| squares.getOrDefault((r / 3) * 3 + c / 3, new HashSet<>()).contains(cell)) {
return false;
}
cols.computeIfAbsent(c, k -> new HashSet<>()).add(cell);
rows.computeIfAbsent(r, k -> new HashSet<>()).add(cell);
squares.computeIfAbsent((r / 3) * 3 + c / 3, k -> new HashSet<>()).add(cell);
}
}
return true;
}
}