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.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
JAVA
方法一
并不知道如何来判断是不是一个可用的数独,只能尝试一下判断已经填写的数字中是否有不满足数独规则的,分别判断行、列、子格。没想到竟然过了,就是效率不高,在3/4左右。。
public class Solution {
static int MAXSIZE = 9;
static int SUBBOXSIZE = 3;
public boolean isValidSudoku(char[][] board) {
if (board.length != MAXSIZE || board[0].length != MAXSIZE){
return false;
}
for (int i = 0; i < MAXSIZE; ++i){
if (!judgeRow(board,i)){
return false;
}
}
for (int i = 0; i < MAXSIZE; ++i){
if (!judgeColumn(board,i)){
return false;
}
}
for (int i = 0; i < MAXSIZE; i += 3){
for(int j = 0; j < MAXSIZE; j += 3){
if (!judgeSubBox(board,i,j)){
return false;
}
}
}
return true;
}
public boolean judgeRow(char[][] board,int row){
HashSet<Character> used = new HashSet<Character>();
for(int i = 0; i < MAXSIZE; ++i){
if(board[row][i] != '.' && used.contains(board[row][i])){
return false;
}else{
used.add(board[row][i]);
}
}
return true;
}
public boolean judgeColumn(char[][] board,int column){
HashSet<Character> used = new HashSet<Character>();
for(int i = 0; i < MAXSIZE; ++i){
if(board[i][column] != '.' && used.contains(board[i][column])){
return false;
}else{
used.add(board[i][column]);
}
}
return true;
}
public boolean judgeSubBox(char[][] board,int row,int column){
HashSet<Character> used = new HashSet<Character>();
for(int i = 0; i < SUBBOXSIZE; ++i){
for (int j = 0; j < SUBBOXSIZE; ++j){
if(board[row + i][column + j] != '.' && used.contains(board[row + i][column + j])){
return false;
}else{
used.add(board[row + i][column + j]);
}
}
}
return true;
}
}