Example #1
0
// Reference implementation of a Sudoku solver
// https://en.wikipedia.org/wiki/Sudoku_solving_algorithms#Backtracking
func (s *Solver) backtrack(b *puzzle.Board) (*puzzle.Board, bool) {
	if b.Solved() {
		return b, true
	}

	for row := 0; row < 9; row++ {
		for col := 0; col < 9; col++ {
			if b.ValueAt(row, col) == 0 {
				for i := 1; i < 10; i++ {
					if b.Allowed(row, col, i) {
						if bb, s := s.backtrack(b.SetAndCopy(row, col, i)); s {
							return bb, s
						}
					}
				}

				// None of the numbers [1,9] can be inserted in this empty cell
				// so the board is unsolvable
				return b, false
			}
		}
	}

	return b, false
}
Example #2
0
// exactCover takes the basic cover and updates it with extra
// contraints for the numbers we have been given through the board
func exactCover(board *puzzle.Board) [][]int {
	base := baseCover()

	for i := 0; i < size; i++ {
		for j := 0; j < size; j++ {
			n := board.ValueAt(i, j)
			if n != 0 {
				for v := 0; v < size; v++ {
					if v != n-1 {
						arr := base[index(i, j, v)]
						for k := range arr {
							arr[k] = 0
						}
					}
				}
			}
		}
	}

	return base
}