Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to these rules:
Note: A Sudoku board (partially filled) could be valid but is not necessarily solvable.
board.length == 9board[i].length == 9board[i][j] is a digit '1'-'9' or '.'Use HashSet to track digits in each row, column, and 3x3 sub-box.
Why this approach works:
Alternative approaches considered:
Example Input:
board = [
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Step-by-step execution:
Final Answer = true (this is a valid Sudoku board)
import java.util.HashSet;
import java.util.Set;
class Solution {
public boolean isValidSudoku(char[][] board) {
int m = board.length;
int n = board[0].length;
// Check rows
for (int i = 0; i < m; i++) {
Set<Character> set = new HashSet<>();
for (int j = 0; j < n; j++) {
char ch = board[i][j];
if (ch != '.') {
if (set.contains(ch))
return false;
else
set.add(ch);
}
}
}
// Check cols
for (int i = 0; i < m; i++) {
Set<Character> set = new HashSet<>();
for (int k = 0; k < m; k++) {
char ch = board[k][i];
if (ch != '.') {
if (set.contains(ch))
return false;
else
set.add(ch);
}
}
}
// Check 3x3 sub-boxes
for (int blockRow = 0; blockRow < 3; blockRow++) {
for (int blockCol = 0; blockCol < 3; blockCol++) {
Set<Character> set = new HashSet<>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
char ch = board[blockRow * 3 + i][blockCol * 3 + j];
if (ch != '.') {
if (set.contains(ch))
return false;
set.add(ch);
}
}
}
}
}
return true;
}
}