LeetCode link

Intuition

  • It’s simple, just build a map to record all the values for each row, col and block.

solution

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
class Solution {
public boolean isValidSudoku(char[][] board) {
Map<Integer, Set<Character>> rowMap = new HashMap<>();
Map<Integer, Set<Character>> colMap = new HashMap<>();
Map<Integer, Set<Character>> blockMap = new HashMap<>();
for (int i = 0; i < 9; i++) {
rowMap.put(i, new HashSet<Character>());
colMap.put(i, new HashSet<Character>());
blockMap.put(i, new HashSet<Character>());
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c = board[i][j];
if (c == '.') {
continue;
}
int block = (int)(i / 3) * 3 + j / 3;
Set<Character> rowSet = rowMap.get(i);
Set<Character> colSet = colMap.get(j);
Set<Character> blockSet = blockMap.get(block);
if (rowSet.contains(c) || colSet.contains(c) || blockSet.contains(c)) {
return false;
}
rowSet.add(c);
colSet.add(c);
blockSet.add(c);
}
}
return true;
}
}

promote

It can use a 2d array instead of HashMap, and make it faster.