-
Notifications
You must be signed in to change notification settings - Fork 0
/
nqueens-cross.go
373 lines (347 loc) · 8.54 KB
/
nqueens-cross.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package main
import(
//"sync"
"sort"
"time"
"flag"
"fmt"
"io"
//"os"
)
var nq = flag.Int("n", 8, "N - the size of the board and amounts of queen to place. N > 0!")
var w = flag.Bool("w", false, "Use modifyed (recursive->iterative) N. Wirth's algorithm, otherwise use T. Bolshakov's algorithm")
func main() {
flag.Parse()
fmt.Printf("Trying to solve N Queens problem for %d Queens on %d x %d board\n", *nq, *nq, *nq);
if *nq <= 0 {
fmt.Println("N=%d, %d<=0, problem solved: no chessboard, no queens!\n", *nq)
return
}
var solutions []Solution
start := time.Now()
if *w {
fmt.Println("Using modifyed (recursive->iterative) N. Wirth algorithm.");
solutions = Wirth(*nq)
} else {
fmt.Println("Using T. Bolshakov's parallel algorithm.")
solutions = Bolshakov(*nq)
}
dur := time.Since(start)
if len(solutions) > 0 {
fmt.Printf("All (%d) solutions for %d took %s\n", len(solutions), *nq, dur.String())
//printSolutions(os.Stdout, solutions)
}else{
fmt.Printf("Solution for %d was not found!\n", *nq)
}
/*
rowsb, rows := []int{1,2,3,4}, []int{0, 0, 0, 0}
fmt.Println("")
for b := 0; b < 3; b++ {
for a := 0; a < 4; a++ {
for r, c := range rowsb { rows[(r+a)%4] = c }
for _, c := range rows {
fmt.Printf("%d, ", c)
}
fmt.Println("")
}
rowsb[b], rowsb[(b+1)%4] = rowsb[(b+1)%4], rowsb[b]
}
*/
}
type Solution struct {
N int
Rows []int
}
type SolutionW struct {
Solution
Cols, Diags, RDiags []bool
}
func compare(s1, s2 *Solution) bool{
if(s1.N == s2.N){
for i,s := range s1.Rows {
if s!=s2.Rows[i] { return s < s2.Rows[i] }
}
}
return s1.N < s2.N
}
type solutionsSorter struct {
sols []Solution
comp func(s1, s2 *Solution) bool // Closure used in the Less method.
}
// Len is part of sort.Interface.
func (s *solutionsSorter) Len() int {
return len(s.sols)
}
// Swap is part of sort.Interface.
func (s *solutionsSorter) Swap(i, j int) {
s.sols[i], s.sols[j] = s.sols[j], s.sols[i]
}
// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.
func (s *solutionsSorter) Less(i, j int) bool {
return s.comp(&s.sols[i], &s.sols[j])
}
func equals(x, y []int) bool{
if len(x)!=len(y) {
return false
}
for i, e := range x {
if e!=y[i] {
return false
}
}
return true
}
func addAllSolutions(s Solution, all []Solution) []Solution{
all = addSolution(s, all)
rows := s.Rows
s.Rows = make([]int, s.N, s.N);
for r,c := range rows { s.Rows[c] = r }
all = addSolution(s, all)
for r,c := range rows { s.Rows[s.N-1-r] = c }
all = addSolution(s, all)
for r,c := range rows { s.Rows[s.N-1-c] = r }
all = addSolution(s, all)
return all
}
func addSolution(s2add Solution, all []Solution) []Solution{
for _, s := range all {
if equals( s2add.Rows, s.Rows ){
return all
}
}
var s1 Solution
s1.N = s2add.N
s1.Rows = make([]int, s1.N, s1.N);
copy(s1.Rows, s2add.Rows)
return append(all, s1)
}
func registerSolution(n int, rows []int/*, cols, diags, rdiags []bool*/) Solution{
var s Solution
s.N = n
s.Rows = make([]int, n, n); copy(s.Rows, rows)
return s
}
func newSolution(n int) SolutionW{
var s SolutionW
s.N = n
s.Rows = make([]int, n, n)
s.Cols = make([]bool, n, n)
s.Diags = make([]bool, 2*n-1, 2*n-1)
s.RDiags = make([]bool, 2*n-1, 2*n-1)
reset( &s )
return s
}
func reset(s *SolutionW){
for i := range s.Rows {
s.Rows[i], s.Cols[i] = -1, true
}
for i := range s.Diags {
s.RDiags[i], s.Diags[i] = true, true
}
}
func printSolution(w io.Writer, s Solution){
for i,r := range s.Rows {
if i == 0 {
fmt.Fprintf(w, "\t%d, ", r+1)
} else if i == s.N-1 {
fmt.Fprintf(w, "%d\n", r+1)
} else {
fmt.Fprintf(w, "%d, ", r+1)
}
}
}
func printSolutions(w io.Writer, solutions []Solution){
if len(solutions)>0 {
fmt.Fprintf(w, "%d (%d):\n", solutions[0].N, len(solutions))
for _,s := range solutions {
printSolution(w, s)
}
}else{
fmt.Fprintln(w, "No solutions!\n")
}
}
// Наивное, прямое, но не рекурсивное решение, скопировано из Вирта.
func Wirth(n int) []Solution{
rows := make([]int, n, n)
cols := make([]bool, n, n)
diags := make([]bool, 2*n-1, 2*n-1)
rdiags := make([]bool, 2*n-1, 2*n-1)
solved := false
solutions := make([]Solution, 0, 1000) // binomial coefficient 2*n-1, n ...
for i:=range rows {
rows[i], cols[i] = 0, true
}
for i:=range diags {
diags[i], rdiags[i] = true, true
}
for row := 0; row<n; {
solved = false
for col := rows[row]; col<n; col++ {
if cols[col] && diags[row+col] && rdiags[n-1+row-col] {
cols[col], diags[row+col], rdiags[n-1+row-col] = false, false, false
rows[row] = col
if row==n-1 {
solutions = addSolution(registerSolution(n, rows/*, cols, diags, rdiags*/), solutions)
cols[col], diags[row+col], rdiags[n-1+row-col] = true, true, true
rows[row] = 0
} else {
solved = true
break
}
}
}
if solved {
row++
}else{
for ; ; {
row--
if row < 0 {
return solutions
}
col := rows[row]
cols[col], diags[row+col], rdiags[n-1+row-col] = true, true, true
for i := row+1; i < n; i++ {
rows[i] = 0
}
if( rows[row] < n-1 ){
rows[row]++; break
}
}
}
}
return solutions
}
func uniq(sent []Solution, sol Solution) bool {
rows, rowsb := make([] int, sol.N, sol.N), make([] int, sol.N, sol.N)
copy(rowsb, sol.Rows)
for b := 0; b < sol.N; b++ {
for a := 0; a < sol.N; a++ {
for r, c := range rowsb { rows[(r+a)%sol.N] = c }
for _,s :=range sent {
if equals(rows, s.Rows) { return false }
}
}
rowsb[b], rowsb[(b+1)%sol.N] = rowsb[(b+1)%sol.N], rowsb[b]
}
return true
}
// Глубоко параллельный алгоритм Тимофея Большакова.
func Bolshakov(n int) []Solution{
if n >= 4 {
solutionsPrev := Wirth(4)
if n == 4 {
return solutionsPrev
}
for i := 5; i<=n; i++ {
//var wg sync.WaitGroup
start := time.Now()
solutions := make([]Solution, 0, 4*len(solutionsPrev)*(2*i+1))
sent := make([]Solution, 0, len(solutionsPrev))
sChan := make(chan Solution, 4*len(solutionsPrev)*(2*i+1))
cnt := 0
for _, sol := range solutionsPrev {
if uniq(sent, sol) {
go func(s Solution){
promote(s, sChan)
}(clone(sol))
sent = addSolution(sol, sent)
cnt++
}
}
fmt.Printf("cnt:%d\n", cnt)
for loop := true; loop; {
s, ok := <- sChan
if(!ok) { break }
if s.N > 0 {
solutions = addAllSolutions(s, solutions)
} else {
cnt--
if cnt==0 { close(sChan) }
}
}
dur := time.Since(start)
sort.Sort(&solutionsSorter{sols:solutions, comp:compare})
//printSolutions(os.Stdout, solutions)
fmt.Printf("All (%d) solutions for %d took %s\n", len(solutions), i, dur.String())
solutionsPrev = solutions
}
return solutionsPrev
}
return make([]Solution, 0, 0)
}
func printBoolArr(arr []bool){
for i,r := range arr {
s := 0
if r {
s = 1
}
if i == 0 {
fmt.Printf("%d, ", s)
} else if i == len(arr)-1 {
fmt.Printf("%d\n", s)
} else {
fmt.Printf("%d, ", s)
}
}
}
func set(r, c int, ns *SolutionW) bool {
if ns.Cols[c] && ns.Diags[r+c] && ns.RDiags[ns.N-1+r-c] {
ns.Rows[r] = c;
ns.Cols[c], ns.Diags[r+c], ns.RDiags[ns.N-1+r-c] = false, false, false
return true
}
return false
}
func clone(s Solution) Solution{
var s1 Solution
s1.N = s.N
s1.Rows = make([] int, s.N, s.N); copy(s1.Rows, s.Rows)
return s1
}
func promote(s Solution, sChan chan Solution) {
//fmt.Println()
//printSolution( os.Stdout, s )
//sols := make([]Solution, 0, s.N*(2*s.N+1))
need, ns := true, newSolution(s.N+1)
rows, rowsb := make([] int, s.N, s.N), make([] int, s.N, s.N)
for y:=0; y<s.N-1; y++ {
for x:=0; x<s.N-1; x++ {
copy(rowsb, s.Rows)
rowsb[y], rowsb[x] = rowsb[x], rowsb[y]
for b := 0; b < s.N; b++ {
for a := 0; a < s.N; a++ {
for r, c := range rowsb { rows[(r+a)%s.N] = c }
for ir := 0; ir<=s.N; ir++ {
for ic :=0; ic<=s.N; ic++{
for r,c := range rows {
nr, nc := r, c
if nr>=ir {nr++}
if nc>=ic {nc++}
if(!set(nr, nc, &ns)){ need=false; break }
}
if(need) {
if set(ir, ic, &ns) {
//fmt.Print("V")
//sols = addSolution(ns.Solution, sols)
sol := clone(ns.Solution)
sChan <- sol
}
//printSolution( os.Stdout, ns.Solution )
}
reset(&ns)
need = true
}
}
}
rowsb[b], rowsb[(b+1)%s.N] = rowsb[(b+1)%s.N], rowsb[b]
}
}
}
/*
for _, sol := range sols {
sChan <- sol
}
*/
var end Solution
sChan <- end
}