查重:
1.标记 Visited:
a. 直接在array中改 (比如word search中把搜索过的字符mark为'#',这样下次再搜时不可能再相等了)
b. 另建一个boolean[ ] visited, 访问过的mark为true.由于此题中元素范围只有1-9,所以index-1来表示该元素。
2. Hash
HashTable: containsKey(Key) containsValue(Value)put(Key, Value)
HashSet: contains(Value) add(Value)
public class Solution {
public boolean isValidSudoku(char[][] board) {
boolean[] isVisited = new boolean[9];
//check Row
for (int i = 0; i < 9; i++) {
Arrays.fill(isVisited, false);
for (int j = 0; j < 9; j++) {
if (!process(isVisited, board[i][j])) {
return false;
}
}
}
//check Column
for (int i = 0; i < 9; i++) {
Arrays.fill(isVisited, false);
for (int j = 0; j < 9; j++) {
if (!process(isVisited, board[j][i])) {
return false;
}
}
}
//check big cell
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
Arrays.fill(isVisited, false);
for (int k = 0; k < 9; k++) {
if (!process(isVisited, board[i*3 + k/3][j*3 + k%3])) {
return false;
}
}
}
}
return true;
}
public boolean process(boolean[] isVisited, char c) {
if (c == '.') return true;
int d = c - '0';
if (d <1 || d >9 || isVisited[d -1] ){
return false;
}
isVisited[d - 1] = true;
return true;
}
}