-
Notifications
You must be signed in to change notification settings - Fork 3
/
nqueens.c
116 lines (89 loc) · 2 KB
/
nqueens.c
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <cilk/cilk.h>
#include "ctimer.h"
unsigned long long todval (struct timeval *tp) {
return tp->tv_sec * 1000 * 1000 + tp->tv_usec;
}
/*
* nqueen 4 = 2
* nqueen 5 = 10
* nqueen 6 = 4
* nqueen 7 = 40
* nqueen 8 = 92
* nqueen 9 = 352
* nqueen 10 = 724
* nqueen 11 = 2680
* nqueen 12 = 14200
* nqueen 13 = 73712
* nqueen 14 = 365596
* nqueen 15 = 2279184
*/
/*
* <a> contains array of <n> queen positions. Returns 1
* if none of the queens conflict, and returns 0 otherwise.
*/
int ok (int n, char *a) {
int i, j;
char p, q;
for (i = 0; i < n; i++) {
p = a[i];
for (j = i + 1; j < n; j++) {
q = a[j];
if (q == p || q == p - (j - i) || q == p + (j - i))
return 0;
}
}
return 1;
}
int nqueens (int n, int j, char *a) {
char *b;
int *count;
int solNum = 0;
if (n == j) {
return 1;
}
count = (int *) alloca(n * sizeof(int));
(void) memset(count, 0, n * sizeof (int));
b = (char *) alloca((j + 1) * sizeof (char));
memcpy(b, a, j * sizeof (char));
cilk_scope {
for (int i = 0; i < n; i++) {
b[j] = i;
if (ok(j + 1, b))
count[i] = cilk_spawn nqueens(n, j + 1, b);
}
}
for (int i = 0; i < n; i++) {
solNum += count[i];
}
return solNum;
}
int main(int argc, char *argv[]) {
int n = 13;
char *a;
int res;
if (argc < 2) {
fprintf (stderr, "Usage: %s [<cilk-options>] <n>\n", argv[0]);
fprintf (stderr, "Use default board size, n = 13.\n");
} else {
n = atoi (argv[1]);
fprintf (stderr, "Running %s with n = %d.\n", argv[0], n);
}
a = (char *) alloca (n * sizeof (char));
res = 0;
ctimer_t t;
ctimer_start(&t);
res = nqueens(n, 0, a);
ctimer_stop(&t);
ctimer_measure(&t);
ctimer_print(t, "nqueens");
if (res == 0) {
fprintf (stderr, "No solution found.\n");
} else {
fprintf (stderr, "Total number of solutions : %d\n", res);
}
return 0;
}