class Solution {
private int findAreaNumber(int i, int j) {
if (i >= 0 && i < 3 && j >= 0 && j < 3) {
return 1;
} else if (i >= 0 && i < 3 && j >= 3 && j < 6) {
return 2;
} else if (i >= 0 && i < 3 && j >= 6 && j < 9) {
return 3;
} else if (i >= 3 && i < 6 && j >= 0 && j < 3) {
return 4;
} else if (i >= 3 && i < 6 && j >= 3 && j < 6) {
return 5;
} else if (i >= 3 && i < 6 && j >= 6 && j < 9) {
return 6;
} else if (i >= 6 && i < 9 && j >= 0 && j < 3) {
return 7;
} else if (i >= 6 && i < 9 && j >= 3 && j < 6) {
return 8;
} else if (i >= 6 && i < 9 && j >= 6 && j < 9) {
return 9;
} else {
return 0;
}
}
public boolean isValidSudoku(char[][] board) {
HashMap<Integer, ArrayList<Integer>> rows = new HashMap<>();
HashMap<Integer, ArrayList<Integer>> columns = new HashMap<>();
HashMap<Integer, ArrayList<Integer>> areas = new HashMap<>();
for (int i=0; i<9; i++) {
for (int j=0; j<9; j++) {
if (board[i][j] == '.') { continue; }
int number = Integer.valueOf(String.valueOf(board[i][j]));
ArrayList<Integer> currentRows = rows.get(i + 1) == null ? new ArrayList<Integer>() : rows.get(i + 1);
ArrayList<Integer> currentColumns = columns.get(j + 1) == null ? new ArrayList<Integer>() : columns.get(j + 1);
// row check
if (currentRows.contains(number)) {
return false;
} else {
currentRows.add(number);
rows.put(i + 1, currentRows);
}
// column check
if (currentColumns.contains(number)) {
return false;
} else {
currentColumns.add(number);
columns.put(j + 1, currentColumns);
}
}
}
// check area
for (int i=0; i<9; i=i+3) {
for (int j=0; j<9; j=j+3) {
for (int r=0; r<3; r++) {
for (int c=0; c<3; c++) {
if (board[i+r][j+c] == '.') { continue; }
int number = Integer.valueOf(String.valueOf(board[i+r][j+c]));
int areaNumber = findAreaNumber(i + r, j + c);
ArrayList<Integer> currentArea = areas.get(areaNumber) == null ? new ArrayList<Integer>() : areas.get(areaNumber);
if (currentArea.contains(number)) {
return false;
} else {
currentArea.add(number);
areas.put(areaNumber, currentArea);
}
}
}
}
}
return true;
}
}