请判定一个数独是否有效
public class Solution {
/**
* @param board: the board
* @return: whether the Sudoku is valid
*/
public boolean isValidSudoku(char[][] board) {
// write your code here
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[i].length; j++){
char mark = board[i][j];
for(int k = j+1; k < board[i].length; k++){
if(mark != '.' && board[i][k] != '.' && mark == board[i][k]){
return false;
}
}
char mark1 = board[j][i];
for(int k = j+1; k < board.length; k++){
if(mark1 != '.' && board[k][i] != '.' && mark1 == board[k][i]){
return false;
}
}
}
char mark2 = board[i][board[i].length - 1];
for(int j = board[i].length - 2; j >= 0; j--){
if(mark2 != '.' && board[i][j] != '.' && mark2 == board[i][j]){
return false;
}
}
char mark3 = board[i][i];
for(int j = i + 1; j < board.length; j++){
if(mark3 != '.' && board[j][j] != '.' && mark2 == board[j][j]){
return false;
}
}
if(i == 0 || i == 3 || i == 6 ){
for(int j = 0; j < 3; j++){
List<Character> data = new ArrayList<>();
for(int m = i; m < i + 3; m++){
for(int k = j * 3; k < 3 + j * 3; k++){
char mark4 = board[m][k];
data.add(mark4);
}
}
for(int m = 0; m < data.size(); m++){
char mark = data.get(m);
for(int n = m + 1; n < data.size(); n++){
if(mark != '.' && data.get(n) != '.' && mark == data.get(n)){
return false;
}
}
}
}
}
}
return true;
}
}
解题思路:
先判断横纵轴的是否存在相同数,再判断交互轴是否存在相同数,最后判断每个小9宫格是否存在相同数。