Saturday, February 22, 2014

Valid Sudoku (Java)

LeetCode


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.

Solution: Helpe table
Declare 9 boolean array with length 9  separately for rows, columns and blocks and hold them in ArrayList. Because the number range of sudoku is 1-9, so each number in each row, col and block should be unique, then we can go through every position of given board, check if the number has been
Found in current row,current column  and current block. If so, return false;

*** Be careful about the index of block in blockChecker



/*
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.
*/
public class ValidSudoku {
public boolean isValidSudoku(char[][] board) {
if (board==null|| board.length!=9 || board[0].length!=9){
return false;
}
// initialize the Checkers
ArrayList<boolean[]> rowChecker=new ArrayList<boolean[]>();
ArrayList<boolean[]> colChecker=new ArrayList<boolean[]>();
ArrayList<boolean[]> blockChecker=new ArrayList<boolean[]>();
for (int i=0; i<9; i++){
rowChecker.add(new boolean[9]);
colChecker.add(new boolean[9]);
blockChecker.add(new boolean[9]);
}
for (int i=0; i<9; i++){
for (int j=0; j<9; j++){
if (board[i][j]=='.'){
continue;
}
// current value, there should be a positin represented of c at each checkers
// pay attention to the indice of block checker
int c= board[i][j]-'1' ;
if (rowChecker.get(j)[c]==true || colChecker.get(i)[c]==true || blockChecker.get(i/3*3+j/3)[c]==true){
return false;
}
else{
rowChecker.get(j)[c]=true;
colChecker.get(i)[c]=true;
blockChecker.get(i/3*3+j/3)[c]=true;
}
}
}
return true;
}
}

No comments:

Post a Comment