Determine whether a Sudoku is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character
Have you met this question in a real interview? .
.
Yes
Example
The following partially filed sudoku is valid.
Note
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Clarification
class Solution {
/**
* @param board: the board
@return: wether the Sudoku is valid
*/
public boolean isValidSudoku(char[][] board) {
if(board == null || board.length == 0 || board[0].length == 0) return false;
int m = 9, n = 9;
// check row
boolean[] visited = new boolean[9];
for(int i = 0; i < m; i++){
Arrays.fill(visited, false);
for(int j = 0; j < n; j++){
if(!precess(visited, board[i][j])) return false;
}
}
for(int i = 0; i < n; i++){
Arrays.fill(visited, false);
for(int j = 0; j < m; j++){
if(!precess(visited, board[j][i])) return false;
}
}
for(int i = 0; i < m; i+=3){
for(int j = 0; j < n; j+=3){
Arrays.fill(visited, false);
for(int k = 0; k < 9; k++){
if(!precess(visited, board[i+k/3][j+k%3])) return false;
}
}
}
return true;
}
private boolean precess(boolean[] visited, char c){
if(c == '.') return true;
int num = c - '0';
if(num > 9 || num < 1 || visited[num-1]) return false;
visited[num-1] = true;
return true;
}
};
No comments:
Post a Comment