I'll help you solve this Sudoku puzzle using Kotlin. Let's break it down into steps:
- First, we'll create a solver that uses backtracking algorithm
- We'll represent the board as a 2D array
- We'll implement functions to check valid moves
- Finally, we'll solve recursively
Here's the solution:
class SudokuSolver {
private val BOARD_SIZE = 9
private val EMPTY_CELL = '.'
fun solveSudoku(board: Array<CharArray>): Boolean {
for (row in 0 until BOARD_SIZE) {
for (col in 0 until BOARD_SIZE) {
if (board[row][col] == EMPTY_CELL) {
for (num in '1'..'9') {
if (isValid(board, row, col, num)) {
board[row][col] = num
if (solveSudoku(board)) {
return true
}
board[row][col] = EMPTY_CELL
}
}
return false
}
}
}
return true
}
private fun isValid(board: Array<CharArray>, row: Int, col: Int, num: Char): Boolean {
// Check row
for (x in 0 until BOARD_SIZE) {
if (board[row][x] == num) return false
}
// Check column
for (x in 0 until BOARD_SIZE) {
if (board[x][col] == num) return false
}
// Check 3x3 box
val startRow = row - row % 3
val startCol = col - col % 3
for (i in 0..2) {
for (j in 0..2) {
if (board[i + startRow][j + startCol] == num) return false
}
}
return true
}
fun printBoard(board: Array<CharArray>) {
for (i in 0 until BOARD_SIZE) {
for (j in 0 until BOARD_SIZE) {
print("${board[i][j]} ")
}
println()
}
}
}
fun main() {
val input = ".....2.7.4....8.1....1.6.......69..8..25.....9.7........9.4..8..8....32.........."
val board = Array(9) { CharArray(9) }
// Convert input string to 2D array
var index = 0
for (i in 0 until 9) {
for (j in 0 until 9) {
board[i][j] = input[index++]
}
}
val solver = SudokuSolver()
println("Original board:")
solver.printBoard(board)
if (solver.solveSudoku(board)) {
println("\nSolved board:")
solver.printBoard(board)
} else {
println("\nNo solution exists")
}
}
This solution uses a backtracking algorithm which:
- Finds an empty cell
- Tries digits 1-9 in that cell
- Checks if the digit is valid in that position
- If valid, recursively tries to solve the rest of the puzzle
- If we can't solve with that digit, we backtrack and try the next digit
The isValid function checks three conditions:
- No duplicate in the same row
- No duplicate in the same column
- No duplicate in the same 3x3 box
When you run this code with your input, it will print both the original and solved Sudoku board. The solution is guaranteed to be correct if one exists, as it systematically tries all possibilities until finding a valid solution.
Would you like me to explain any specific part of the solution in more detail?