-
Notifications
You must be signed in to change notification settings - Fork 0
/
backTrackingWithOrderedVals.go
84 lines (78 loc) · 2.1 KB
/
backTrackingWithOrderedVals.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"time"
)
const SQUARE_LENGTH = 9
const ROOT = 3
func isSolved(board [][]byte) bool {
var solved = true
for ii := 0; ii < SQUARE_LENGTH; ii++ {
for jj := 0; jj < SQUARE_LENGTH; jj++ {
if board[ii][jj] == '.' {
solved = false
break
}
}
}
return solved
}
func isValid(board [][]byte, row, column int, val byte) bool {
for ii := 0; ii < SQUARE_LENGTH; ii++ {
// Is this value already in this column?
if board[ii][column] == val {
return false
}
// Is this value already in this row?
if board[row][ii] == val {
return false
}
// Is this value already in this box?
boxRow := ((row / ROOT) * ROOT) + (ii / ROOT)
boxColumn := ((column / ROOT) * ROOT) + (ii % ROOT)
if board[boxRow][boxColumn] == val {
return false
}
}
// If this value is not found in any conflicting locations, it is valid.
return true
}
// Solve the sudoku puzzle.
func solve(board [][]byte, heuristicQueue []int) bool {
var currii int
var currjj int
if len(heuristicQueue) == 0 {
solved := isSolved(board)
return solved
} else {
currii = heuristicQueue[0] / 10
currjj = heuristicQueue[0] % 10
}
for x := 0; x < SQUARE_LENGTH; x++ {
valQ := []byte {}
val := valQ[x]
// Check to see if this value fits into the current solution.
if isValid(board, currii, currjj, val) {
board[currii][currjj] = val
if solve(board, heuristicQueue[1:]) {
return true
} else {
// We leave the '.' in this box so we can see where it went wrong.
board[currii][currjj] = '.'
}
}
}
// No values fit. Break this branch.
return false
}
// Invokes a helper method that can recursively call itself then return the valid solution.
func main() {
board := [][]byte {{}}
var heuristicQueue = []int{}
start := time.Now()
solve(board, heuristicQueue)
t := time.Now()
elapsed := t.Sub(start)
fmt.Print(elapsed)
fmt.Print("\n\n")
}