valid sudoku


Determine if a Sudoku is valid, according to:

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

img

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class {
public boolean isValidSudoku(char[][] board) {
for(int i=0; i < 9; i++) {
HashSet<Character> row = new HashSet<Character>();
HashSet<Character> col = new HashSet<Character>();
HashSet<Character> cube = new HashSet<Character>();
for(int j=0; j < 9; j++) {
if(board[i][j] != '.' && !row.add(board[i][j]))
return false;
if(board[j][i] != '.' && !col.add(board[j][i]))
return false;
int cuberow = 3*(i/3);
int cubecol = 3*(i%3);
if(board[cuberow+j/3][cubecol+j%3]!='.'&&!cube.add(board[cuberow+j/3][cubecol+j%3]))
return false;
}
}
return true;
}
}