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.
Solution:
Trivial implementation question.
Solution:
Trivial implementation question.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
public class Solution {
public boolean isValidSudoku(char[][] board) {
//check rows
for(int i = 0; i < 9; i++){
int[] a = new int[10];
for(int j = 0; j < 9; j++){
if(board[i][j] == '.') continue;
a[board[i][j] - '0']++;
if(a[board[i][j] - '0'] > 1) return false;
}
}
//check cols
for(int j = 0; j < 9; j++){
int[] a = new int[10];
for(int i = 0; i < 9; i++){
if(board[i][j] == '.') continue;
a[board[i][j] - '0']++;
if(a[board[i][j] - '0'] > 1) return false;
}
}
//check sub-boxes
for(int startRow = 0; startRow <= 6; startRow+=3){
for(int startCol = 0; startCol <= 6; startCol+=3){
int[] a = new int[10];
for(int i = startRow; i < startRow+3; i++){
for(int j = startCol; j < startCol+3; j++){
if(board[i][j] == '.') continue;
a[board[i][j] - '0']++;
if(a[board[i][j] - '0'] > 1) return false;
}
}
}
}
return true;
}
}
No comments:
Post a Comment