// solveByGuessing selects the position with minimum possibilities out of the remaining empty positions. // For each of the possible values, the grid is solved. For each conflict, the state is backtracked. // If no conflict is there, then recursively solveByGuessing on the remaining empty positions. // Prints the solution, if found. Also increments the number of solutions. func solveByGuessing(grid *datatypes.Grid, positions map[datatypes.Position]bool, iteration int) { // if all positions have been filled, then return if len(positions) == 0 { numSolutions++ grid.Print() return } // copy remaining positions to next iteration, and start guessing for the position with minimum possibilities. pos := copyValuesForNextIteration(grid, positions, iteration) existingValue := grid[pos.X][pos.Y].IterationValues[iteration] for val := range existingValue.Possible { // update the cell with val for next iteration nextValue := grid[pos.X][pos.Y].IterationValues[iteration+1] *grid[pos.X][pos.Y].Val = val *nextValue.Val = val for key := range nextValue.Possible { if key != val { delete(nextValue.Possible, key) } } // start solving using the set value. if !eliminateUsingGivenValues(grid, iteration+1, pos.X, pos.Y, val) { // if no conflict, then call solveByGuessing for remaining positions. updatedPositions := remainingPositions(grid, positions) solveByGuessing(grid, updatedPositions, iteration+1) } // backtrack to previous state copyValuesForNextIteration(grid, positions, iteration) } return }
// setInput creates the initial grid for testing. func setInput(grid *datatypes.Grid) int { setValue(grid, 0, 4, 4) setValue(grid, 0, 5, 5) setValue(grid, 1, 0, 8) setValue(grid, 1, 6, 2) setValue(grid, 1, 8, 7) setValue(grid, 2, 2, 2) setValue(grid, 2, 8, 4) setValue(grid, 3, 2, 6) setValue(grid, 3, 6, 3) setValue(grid, 3, 8, 2) setValue(grid, 4, 3, 1) setValue(grid, 5, 0, 2) setValue(grid, 5, 2, 7) setValue(grid, 5, 3, 4) setValue(grid, 5, 6, 6) setValue(grid, 6, 0, 6) setValue(grid, 6, 1, 4) setValue(grid, 6, 4, 9) setValue(grid, 6, 5, 8) setValue(grid, 7, 0, 7) setValue(grid, 7, 1, 9) setValue(grid, 7, 5, 4) setValue(grid, 8, 7, 3) grid.Print() return 23 }