-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathValidSudoku.kt
65 lines (59 loc) · 2.08 KB
/
ValidSudoku.kt
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* 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 '.'.
*
* Accepted.
*/
class ValidSudoku {
fun isValidSudoku(board: Array<CharArray>?): Boolean {
if (board == null || board.size != 9 && board[0].size != 9) {
return false
}
val mapRow = mutableMapOf<Char, Boolean>()
val mapColumn = mutableMapOf<Char, Boolean>()
for (i in 0..8) {
for (j in 0..8) {
if (board[i][j] in '1'..'9') {
if (mapRow.getOrDefault(board[i][j], false)) {
return false
} else {
mapRow.put(board[i][j], true)
}
} else if (board[i][j] != '.') {
return false
}
if (board[j][i] in '1'..'9') {
if (mapColumn.getOrDefault(board[j][i], false)) {
return false
} else {
mapColumn.put(board[j][i], true)
}
} else if (board[j][i] != '.') {
return false
}
}
mapRow.clear()
mapColumn.clear()
}
val mapBlock = mutableMapOf<Char, Boolean>()
for (i in 0..8 step 3) {
for (j in 0..8 step 3) {
for (m in 0..2) {
for (n in 0..2) {
if (board[i + m][j + n] in '1'..'9') {
if (mapBlock.getOrDefault(board[i + m][j + n], false)) {
return false
} else {
mapBlock.put(board[i + m][j + n], true)
}
} else if (board[i + m][j + n] != '.') {
return false
}
}
}
mapBlock.clear()
}
}
return true
}
}