BiruLyu
5/22/2017 - 10:32 PM

## 36. Valid Sudoku.java

``````class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""

#Using hashSet to store appeared number
rowSets = [ [] for i in range(9) ];
colSets = [ [] for i in range(9) ];
gridSets = [ [] for i in range(9) ];

for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] != '.':

if board[i][j] in rowSets[i]:
return False;
if board[i][j] in colSets[j]:
return False;

k = i / 3 * 3 + j / 3;
if board[i][j] in gridSets[k]:
return False;

rowSets[i].append(board[i][j]);
colSets[j].append(board[i][j]);
gridSets[k].append(board[i][j]);

return True;``````
``````public class Solution {
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 rowIndex = 3*(i/3) + j/3;
int colIndex = 3*(i%3) + j%3;

if(board[rowIndex][colIndex] != '.' && !cube.add(board[rowIndex][colIndex])){
return false;
}
}
}
return true;
}
}``````