Skip to content

Instantly share code, notes, and snippets.

@Mardiniii
Last active April 15, 2018 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mardiniii/66507409647f93e95cdcf7f114b75a2c to your computer and use it in GitHub Desktop.
Save Mardiniii/66507409647f93e95cdcf7f114b75a2c to your computer and use it in GitHub Desktop.
Snippet for medium post
// Solve algorithm
func (s *Sudoku) Solve() bool {
// Find the next pending position in the board
pending, row, col := s.pendingPositions()
// If there aren't more pending positions we did
// and the problem is solved
if !pending {
return true
}
// If not, let's try to find a solution for the pending position
// in row and col. We will try with digits from 1 to 9
for i := 1; i <= 9; i++ {
// Check is the current digit is valid for the given position
// This function checks row, column and box validity
if s.valid(i, row, col) {
// If is valid assign this value to the given position
s.grid[row][col] = i
// Recursive call to Solve method. If the Sudoku
// is done return true
if s.Solve() {
return true
}
// If the current value does not fixed the Sudoku we
// undo the changes (Backtracking comes to scene!!!)
// and we try with the next one
s.grid[row][col] = PENDING
}
}
// We don't find any solution for the Sudoku problem
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment