-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnqueens2.b
101 lines (94 loc) · 1.57 KB
/
nqueens2.b
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
implement Command;
include "cmd.m";
x := array[32] of { * => 0};
l := 1;
n := 4;
solutions := 0;
lcnt := array[32] of { * => 0};
t := 1;
a := big 0;
b := big 0;
c := big 0;
main(argv: list of string)
{
argv = tl argv;
if (len argv > 0)
n = int hd argv;
print("nqueens 7.2.2B* n=%d\n", n);
nqueens();
print("%d solutions\n", solutions);
print("profile (");
for(i:=1;i<=n;i++){
print("%d, ", lcnt[i]);
}
print("%d)\n", solutions);
}
visit()
{
solutions++;
return;
for(i := 1; i <= n; i++) {
print("%d", x[i]);
}
print("\n");
}
pass(): int
{
if ((a & big (1<<t)) > big 0)
return 0;
if ((b & big (1<<(t+l-1))) > big 0)
return 0;
if ((c & big (1<<(t-l+n))) > big 0)
return 0;
a |= big 1<<t;
b |= big 1<<(t+l-1);
c |= big 1<<(t-l+n);
x[l] = t;
if(0)print("l=%d,x=%d,t=%d\n", l,x[l],t);
l++;
return 1;
}
nqueens()
{
backtrack := 0;
b2: for(;;) {
if(0)print("b2: l=%d x=%d t=%d\n", l, x[l], t);
if (l > n) {
visit();
backtrack = 1;
} else {
t = 1;
}
lcnt[l]++;
b3: for(;;) {
if(0)print("b3: l=%d x=%d t=%d\n", l, x[l], t);
if (!backtrack) {
bp := pass();
if (bp) {
continue b2;
}
}
b4: for(;;) {
if(0)print("b4:l=%d x=%d t=%d\n", l, x[l], t);
if (!backtrack) {
if (t < n) {
t++;
continue b3;
}
}
# backtrack
if(0)print("backtrack\n");
backtrack = 0;
l--;
if (l > 0) {
t = x[l];
c &= big 16rFFFFFFFF ^ big (1<<t-l+n);
b &= big 16rFFFFFFFF ^ big (1<<t+l-1);
a &= big 16rFFFFFFFF ^ big (1<<t);
continue b4;
} else
return;
}
}
}
}