-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidsudoku.java
31 lines (28 loc) · 1.2 KB
/
validsudoku.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.HashSet;
public class Solution {
public boolean isValidSudoku(char[][] board) {
// HashSet to track the numbers seen in rows, columns, and sub-grids
for (int i = 0; i < 9; i++) {
HashSet<Character> rowSet = new HashSet<>();
HashSet<Character> colSet = new HashSet<>();
HashSet<Character> subGridSet = new HashSet<>();
for (int j = 0; j < 9; j++) {
// Check the row
if (board[i][j] != '.' && !rowSet.add(board[i][j])) {
return false; // Duplicate in row
}
// Check the column
if (board[j][i] != '.' && !colSet.add(board[j][i])) {
return false; // Duplicate in column
}
// Check the 3x3 sub-grid
int subGridRow = 3 * (i / 3) + j / 3;
int subGridCol = 3 * (i % 3) + j % 3;
if (board[subGridRow][subGridCol] != '.' && !subGridSet.add(board[subGridRow][subGridCol])) {
return false; // Duplicate in sub-grid
}
}
}
return true; // If no duplicates were found, return true
}
}