Skip to content

Instantly share code, notes, and snippets.

@dipendra-sharma
Created April 5, 2025 12:12
Show Gist options
  • Save dipendra-sharma/ffe72c2dfdc734de930d3488e64190ad to your computer and use it in GitHub Desktop.
Save dipendra-sharma/ffe72c2dfdc734de930d3488e64190ad to your computer and use it in GitHub Desktop.
SudokuSolver in kotlin
class SudokuSolver(private val board: Array<IntArray>) {
fun solve(): Boolean {
val emptyCell = findEmptyCell() ?: return true
for (number in 1..9) {
if (isValid(emptyCell.first, emptyCell.second, number)) {
board[emptyCell.first][emptyCell.second] = number
if (solve()) {
return true
}
board[emptyCell.first][emptyCell.second] = 0 // Backtrack
}
}
return false
}
private fun findEmptyCell(): Pair<Int, Int>? {
for (i in board.indices) {
for (j in board[i].indices) {
if (board[i][j] == 0) {
return Pair(i, j)
}
}
}
return null
}
private fun isValid(row: Int, col: Int, number: Int): Boolean {
return !isInRow(row, number) && !isInColumn(col, number) && !isInBox(row, col, number)
}
private fun isInRow(row: Int, number: Int): Boolean {
return board[row].contains(number)
}
private fun isInColumn(col: Int, number: Int): Boolean {
return board.any { it[col] == number }
}
private fun isInBox(row: Int, col: Int, number: Int): Boolean {
val boxRowStart = row - row % 3
val boxColStart = col - col % 3
for (i in 0 until 3) {
for (j in 0 until 3) {
if (board[boxRowStart + i][boxColStart + j] == number) {
return true
}
}
}
return false
}
}
// Example usage
fun main() {
val board = arrayOf(
intArrayOf(5, 3, 0, 0, 7, 0, 0, 0, 0),
intArrayOf(6, 0, 0, 1, 9, 5, 0, 0, 0),
intArrayOf(0, 9, 8, 0, 0, 0, 0, 6, 0),
intArrayOf(8, 0, 0, 0, 6, 0, 0, 0, 3),
intArrayOf(4, 0, 0, 8, 0, 3, 0, 0, 1),
intArrayOf(7, 0, 0, 0, 2, 0, 0, 0, 6),
intArrayOf(0, 6, 0, 0, 0, 0, 2, 8, 0),
intArrayOf(0, 0, 0, 4, 1, 9, 0, 0, 5),
intArrayOf(0, 0, 0, 0, 8, 0, 0, 7, 9)
)
val solver = SudokuSolver(board)
if (solver.solve()) {
println("Sudoku solved:")
board.forEach { println(it.joinToString(" ")) }
} else {
println("No solution exists.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment