【问题描述】
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.
Subscribe to see which companies asked this question
Show Similar Problems
【思路】
使用HashSet依次按行、列、小格检查。
【code】
public class Solution {
public boolean isValidSudoku(char[][] board) {
Set<Character> set = new HashSet<Character>();
// row
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
continue;
}
if (set.contains(board[i][j])) {
return false;
}
set.add(board[i][j]);
}
set.clear();
}
// column
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[j][i] == '.') {
continue;
}
if (set.contains(board[j][i])) {
return false;
}
set.add(board[j][i]);
}
set.clear();
}
// sub-grid
for (int i = 0; i < 9; i++) {
for (int j = i / 3 * 3; j < i / 3 * 3 + 3; j++) {
for (int k = (i % 3) * 3; k < (i % 3) * 3 + 3; k++) {
if (board[j][k] == '.') {
continue;
}
if (set.contains(board[j][k])) {
return false;
}
set.add(board[j][k]);
}
}
set.clear();
}
return true;
}
}