Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
Solution1:Regular 方法 global 3 * 9 * 9 Hashset
实现1a: 用ArrayList<set>
实现1b: 其实可以直接二位数组对应位置boolean
Solution2:tmp 3 * 9 Hashset
思路:1行/1列/1Box 各用一个hashset,i次遍历,因为是正方形对称,所以可以同时check的是第i行和第i列(by i, j 调换),并找到box位置check。
Time Complexity: O(n^2) Space Complexity: O(n^2) n*n矩阵
Solution1a Code:
class Solution {
public boolean isValidSudoku(char[][] board) {
ArrayList<HashSet<Character>> row = new ArrayList<HashSet<Character>>(); // max: 9x9
ArrayList<HashSet<Character>> col = new ArrayList<HashSet<Character>>(); // max: 9x9
ArrayList<HashSet<Character>> box = new ArrayList<HashSet<Character>>(); // max: 9x9
for(int i = 0; i < board.length; ++i) row.add(new HashSet<Character>());
for(int i = 0; i < board.length; ++i) col.add(new HashSet<Character>());
for(int i = 0; i < board.length; ++i) box.add(new HashSet<Character>());
for(int i = 0; i < board.length; ++i) {
for(int j = 0; j < board[0].length; ++j) {
if(board[i][j] == '.') continue;
// check row and col
if(!row.get(i).add(board[i][j]) || !col.get(j).add(board[i][j])) {
return false;
}
// check box
int box_num = i / 3 * 3 + j / 3;
if(!box.get(box_num).add(board[i][j])) {
return false;
}
}
}
return true;
}
}
Solution1b Code:
class Solution {
public boolean isValidSudoku(char[][] board) {
boolean[][] row = new boolean[9][9];
boolean[][] col = new boolean[9][9];
boolean[][] box = new boolean[9][9];
for(int i = 0; i < board.length; ++i) {
for(int j = 0; j < board[0].length; ++j) {
if(board[i][j] == '.') continue;
int num = board[i][j] - '0' - 1;
// check row and col
if(row[i][num] || col[j][num]) {
return false;
}
// check box
int box_num = i / 3 * 3 + j / 3;
if(box[box_num][num]) {
return false;
}
// update
row[i][num] = col[j][num] = box[box_num][num] = true;
}
}
return true;
}
}
Solution2 Code:
class Solution {
public boolean isValidSudoku(char[][] board) {
for(int i = 0; i < 9; i++){
HashSet<Character> row = new HashSet<Character>();
HashSet<Character> column = new HashSet<Character>();
HashSet<Character> box = new HashSet<Character>();
for (int j = 0; j < 9; j++){
if(board[i][j] != '.' && !row.add(board[i][j])) {
return false;
}
if(board[j][i]!='.' && !column.add(board[j][i])) {
return false;
}
int RowIndex = 3 * (i / 3);
int ColIndex = 3 * (i % 3);
if(board[RowIndex + j / 3][ColIndex + j % 3] != '.' && !box.add(board[RowIndex + j / 3][ColIndex + j % 3])) {
return false;
}
}
}
return true;
}
}