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.
这道题我刚开始还以为要求解这个数独呢,吓坏了,后来发现只需要判断初始给的这个数独是不是合法就行了,没什么难度。
最难的地方就在于用一个四层循环取出这大数独中的九个子正方形,然后判断~代码如下:
package datastru;
public class Solution {
public boolean isValidSudoku(char[][] board) {
for(int i = 0; i < 9; i++){
if(check(board[i])){
continue;
}else{
return false;
}
}
char[] ch = new char[9];
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
ch[j] = board[j][i];
}
if(check(ch)){
continue;
}else{
return false;
}
}
int line = 0;
int col = 0;
for(int m = 0; m < 3; m++){
int index = 0;
for(int n = 0; n < 3; n++){
for(int i = 0; i < 3 ; i++){
for(int j = 0; j < 3; j++){
ch[index++] = board[i+line*3][j+col*3];
}
}
col++;
index = 0;
if(check(ch)){
continue;
}else{
return false;
}
}
line++;
col = 0;
}
return true;
}
private boolean check(char[] ch){
boolean[] flags = new boolean[9];
for(char c : ch){
if(c !='.'){
int num = Integer.parseInt(String.valueOf(c));
if(flags[num-1] == false){
flags[num-1] = true;
}else{
return false;
}
}
}
return true;
}
public static void main(String[] args){
Solution sol = new Solution();
// char[][] nums = {{'.','8','7','6','5','4','3','2','1'},["..5.....6","....14...",".........",".....92..","5....2...",".......3.","...54....","3.....42.","...27.6.."]
// {'2','.','.','.','.','.','.','.','.'},
// {'3','.','.','.','.','.','.','.','.'},
// {'4','.','.','.','.','.','.','.','.'},
// {'5','.','.','.','.','.','.','.','.'},
// {'6','.','.','.','.','.','.','.','.'},
// {'7','.','.','.','.','.','.','.','.'},
// {'8','.','.','.','.','.','.','.','.'},
// {'9','.','.','.','.','.','.','.','.'}};
char[][] nums = {{'.','.','5','.','.','.','.','.','6'},
{'.','.','.','.','1','4','.','.','.'},
{'.','.','.','.','.','.','.','.','.'},
{'.','.','.','.','.','9','2','.','.'},
{'5','.','.','.','.','2','.','.','.'},
{'.','.','.','.','.','.','.','3','.'},
{'.','.','.','5','4','.','.','.','.'},
{'3','.','.','.','.','.','4','2','.'},
{'.','.','.','2','7','.','6','.','.'}};
boolean result = sol.isValidSudoku(nums);
System.out.println(result);
}
}