Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updated sudoko.go with the solution code (by Dev Narula) #61

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions sudoku.go
Original file line number Diff line number Diff line change
@@ -1 +1,63 @@
package main

func SolveSudoku(board [][]int) [][]int {
out := make([][]int, len(board))
for i := range board {
out[i] = make([]int, len(board[i]))
copy(out[i], board[i])
}
solve(&out)
return out
}

func solve(board *[][]int) bool {
empty := []int{}
for i := 0; i < 9; i++ {
for j := 0; j < 9; j++ {
if (*board)[i][j] == 0 {
empty = append(empty, i, j)
}
}
}
if len(empty) == 0 {
//finished solving sudoku, no empty cells
return true
}

r, c := empty[0], empty[1]

for num := 1; num <= 9; num++ {
if isValid(*board, r, c, num) {
(*board)[r][c] = num
//recursively determine if num is valid for board[r][c]
if solve(board) {
return true
}
//if board[r][c] = num is invalid, then reset the cell
(*board)[r][c] = 0
}
}

return false // No valid number found for the current cell
}

func isValid(board [][]int, row, col, num int) bool {
// validate row and col
for i := 0; i < 9; i++ {
if board[row][i] == num || board[i][col] == num {
return false
}
}

// valid 3x3 subgrid for duplicates
x, y := 3*(row/3), 3*(col/3)
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if board[x+i][y+j] == num {
return false
}
}
}
//return true if grid is valid
return true
}
Loading