g0001_0100.s0036_valid_sudoku.Solution.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0036_valid_sudoku
// #Medium #Top_Interview_Questions #Array #Hash_Table #Matrix #Data_Structure_I_Day_5_Array
// #2023_07_05_Time_181_ms_(95.15%)_Space_40_MB_(62.78%)
class Solution {
private var j1 = 0
private val i1 = IntArray(9)
private val b1 = IntArray(9)
fun isValidSudoku(board: Array): Boolean {
for (i in 0..8) {
for (j in 0..8) {
val res = checkValid(board, i, j)
if (!res) {
return false
}
}
}
return true
}
private fun checkValid(board: Array, i: Int, j: Int): Boolean {
if (j == 0) {
j1 = 0
}
if (board[i][j] == '.') {
return true
}
val `val` = board[i][j] - '0'
if (j1 == j1 or (1 shl `val` - 1)) {
return false
}
j1 = j1 or (1 shl `val` - 1)
if (i1[j] == i1[j] or (1 shl `val` - 1)) {
return false
}
i1[j] = i1[j] or (1 shl `val` - 1)
val b = i / 3 * 3 + j / 3
if (b1[b] == b1[b] or (1 shl `val` - 1)) {
return false
}
b1[b] = b1[b] or (1 shl `val` - 1)
return true
}
}