Example
Solution 1: Brute Force
Time complexity:O(9^2), space complexity: O()
class Solution {
public boolean isValidSudoku(char[][] board) {
//check row
for(int i = 0; i < 9; i++) {
Set<Character> chars = new HashSet();
for(int j = 0; j < 9; j++) {
//System.out.print("("+i + "," + j + "):" +board[i][j] + "; ");
if(board[i][j] != '.') {
if(chars.contains(board[i][j]))
return false;
else
chars.add(board[i][j]);
}
}
}
//check column
for(int i = 0; i < 9; i++) {
Set<Character> chars = new HashSet();
for(int j = 0; j < 9; j++) {
if(board[j][i] != '.') {
if(chars.contains(board[j][i]))
return false;
else
chars.add(board[j][i]);
}
}
}
//check box
for(int k = 0; k < 9; k++) {
Set<Character> chars = new HashSet();
for(int i = 0; i < 3; i++) {
int row = (i + k*3) % 9;
for(int j = 0; j < 3; j++) {
int col = (j + k/3*3) ;
if(board[row][col] != '.') {
if(chars.contains(board[row][col]))
return false;
else
chars.add(board[row][col]);
}
}
}
}
return true;
}
}
Solution 2: check row, column & box at the same time
class Solution {
public boolean isValidSudoku(char[][] board) {
for (int i = 0; i < 9; i++) {
HashSet<Character> row = new HashSet<>();
HashSet<Character> column = new HashSet<>();
HashSet<Character> cube = new HashSet<>();
for (int j = 0; j < 9; j++) {
// 检查第i行,在横坐标位置
if (board[i][j] != '.' && !row.add(board[i][j]))
return false;
// 检查第i列,在纵坐标位置
if (board[j][i] != '.' && !column.add(board[j][i]))
return false;
// 行号+偏移量
int RowIndex = 3 * (i / 3) + j / 3;
// 列号+偏移量
int ColIndex = 3 * (i % 3) + j % 3;
//每个小九宫格,总共9个
if (board[RowIndex][ColIndex] != '.'
&& !cube.add(board[RowIndex][ColIndex]))
return false;
}
}
return true;
}
}
Reference
https://blog.csdn.net/mine_song/article/details/70207326