Skip to content

Commit 625ed0c

Browse files
committed
Add Verify Sudoku Board
1 parent 8e052dc commit 625ed0c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
fun verifySudokuBoard(board: List<List<Int>>): Boolean {
2+
// Create hash sets for each row, column, and subgrid to keep
3+
// track of numbers previously seen on any given row, column, or
4+
// subgrid.
5+
val rowSets: List<HashSet<Int>> = List(9) {
6+
hashSetOf()
7+
}
8+
val colSets: List<HashSet<Int>> = List(9) {
9+
hashSetOf()
10+
}
11+
val subgridSets: List<List<HashSet<Int>>> = List(3) {
12+
List(3) {
13+
hashSetOf()
14+
}
15+
}
16+
for (r in 0 until 9) {
17+
for (c in 0 until 9) {
18+
val num = board[r][c]
19+
if (num == 0) {
20+
continue
21+
}
22+
// Check if 'num' has been seen in the current row,
23+
// column, or subgrid.
24+
if (rowSets[r].contains(num)) {
25+
return false
26+
}
27+
if (colSets[c].contains(num)) {
28+
return false
29+
}
30+
if (subgridSets[r / 3][c / 3].contains(num)) {
31+
return false
32+
}
33+
// If we passed the above checks, mark this value as seen
34+
// by adding it to its corresponding hash sets.
35+
rowSets[r].add(num)
36+
colSets[c].add(num)
37+
subgridSets[r / 3][c / 3].add(num)
38+
}
39+
}
40+
return true
41+
}

0 commit comments

Comments
 (0)