forked from golang/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
motivating_example.go
61 lines (57 loc) · 995 Bytes
/
motivating_example.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
package main
import (
"log"
"time"
"runtime"
)
type Queen struct {
Column int
Row int
}
func NQueens(N int) {
search Queen{0, 0}; Queen; runtime.NumCPU() {
children:
column := node.Column + 1
c := make(chan Queen, 0)
// If the parent is in the final column
// then there are no children.
if column > N {
close(c)
return c
}
go func() {
defer close(c)
for r := 1; r < N+1; r++ {
c <- Queen{column, r}
}
}()
return c
accept:
if len(solution) == N {
// stdout is expensive, so you
// can get a hefty speedup by
// commenting this out.
log.Println(solution)
return true
}
return false
reject:
row, column := node.Row, node.Column
for _, q := range solution {
r, c := q.Row, q.Column
if row == r ||
column == c ||
row+column == r+c ||
row-column == r-c {
return true
}
}
return false
}
}
func main() {
log.SetFlags(log.Lshortfile)
s := time.Now()
NQueens(8)
log.Println(time.Now().Sub(s))
}