-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnqueens.b
101 lines (93 loc) · 1.42 KB
/
nqueens.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};
di := array[32] of { * => 1};
l := 1;
n := 4;
solutions := 0;
lcnt := array[32] of { * => 0};
main(argv: list of string)
{
argv = tl argv;
if (len argv) 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");
}
updated(): int
{
if(di[l] < n) {
di[l] = di[l] + 1;
x[l] = di[l];
return 0;
} else {
return 1;
}
}
pass(): int
{
for(j:=1; j <= l; j++) {
for(k:=j+1; k <= l; k++) {
z := x[k] - x[j];
if (z < 0) z = -z;
if ((x[j] == x[k]) || (z == k-j))
return 0;
}
}
return 1;
}
nqueens()
{
backtrack := 0;
b2: for(;;) {
if (l > n) {
visit();
backtrack = 1;
} else {
x[l] = 1;
}
if(0)print("l=%d x=%d\n", l, x[l]);
lcnt[l]++;
b3: for(;;) {
if (!backtrack) {
b := pass();
if(0)print("pass %d\n", b);
if (b) {
l++;
continue b2;
}
}
b4: for(;;) {
if (!backtrack) {
ismax := updated();
if(0)print("ismax %d, x[%d]=%d\n", ismax, l, x[l]);
if (!ismax)
continue b3;
}
# backtrack
if(0)print("backtrack\n");
backtrack = 0;
di[l] = 1;
l--;
if (l > 0)
continue b4;
else
return;
}
}
}
}