Example: Valid SUDOKU - rFronteddu/general_wiki GitHub Wiki
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. Note:
A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules.
class Solution {
public boolean isValidSudoku(char[][] board) {
Set<Character> validSet = new HashSet<>(Arrays.asList('1', '2', '3', '4', '5', '6', '7', '8', '9'));
HashMap<Integer, HashSet<Character>> rows = new HashMap<>();
HashMap<Integer, HashSet<Character>> columns = new HashMap<>();
HashMap<Integer, HashSet<Character>> subBoxes = new HashMap<>();
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < board[0].length; c++) {
Character value = board[r][c];
if(value == '.') {
continue;
}
if (!validSet.contains(value)) {
return false;
}
// rows
var set = rows.computeIfAbsent(r, k -> new HashSet<>());
if (!set.add(value)) {
return false;
}
// columns
set = columns.computeIfAbsent(c, k -> new HashSet<>());
if (!set.add(value)) {
return false;
}
// sub boxes, in a standard sudoku
// there are 9 3x3 sub-boxes
int key = 3 * (r/3) + c/3;
set = subBoxes.computeIfAbsent(key, k -> new HashSet<>());
if (!set.add(value)) {
return false;
}
}
}
return true;
// another solution is to treat each row/columns/sub as a key:
/*
Set<String> seen = new HashSet<>();
for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
char value = board[r][c];
if (value == '.') {
continue; // Skip empty cells
String rowKey = value + " in row " + r;
String colKey = value + " in col " + c;
String boxKey = value + " in box " + r/3 + "-" + c/3;
if (!seen.add(rowKey) || !seen.add(colKey) || !seen.add(boxKey)) {
return false; // Duplicate found
}
}
}
*/
}
}