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 '.'
A partially filled sudoku which is valid.
一刷
题解:
验证数独,分三次验证行,列以及9个3x3子块就可以了。用set验证重复问题
Time Complexity - O(n2), Space Complexity - O(1)。
public class Solution {
public boolean isValidSudoku(char[][] board) {
if(board == null || board.length != 9 || board[0].length!=9) return false;
Set<Integer> set = new HashSet<>();
for(int i=0; i<9; i++){//row don't have duplicate
set.clear();
for(int j=0; j<9; j++){
if(board[i][j] != '.' && !set.add(board[i][j] - '0'))//empty or contains duplicate one
return false;
}
}
for(int j=0; j<9; j++){//col don't have duplicate
set.clear();
for(int i=0; i<9; i++){
if(board[i][j] != '.' && !set.add(board[i][j] - '0'))//empty or contains duplicate one
return false;
}
}
for(int i=1; i<9; i+=3){
for(int j=1; j<9; j+=3){
set.clear();
for(int k=-1; k<=1; k++){
for(int l = -1; l<=1; l++){
if(board[i+k][j+l] != '.' && !set.add(board[i+k][j+l] - '0'))//empty or contains duplicate one
return false;
}
}
}
}
return true;
}
}