Last active
April 15, 2018 16:44
-
-
Save Mardiniii/66507409647f93e95cdcf7f114b75a2c to your computer and use it in GitHub Desktop.
Snippet for medium post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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