queens.c
1.93 KB
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
/*
* queens.c
*
* Created on: 26/04/2015
* Author: pedro
*
* http://www.csplib.org/Problems/prob054/
* https://www.cril.univ-artois.fr/~lecoutre/benchmarks.html#
* https://github.com/MiniZinc/minizinc-benchmarks/tree/master/queens
*
* N-queens problem:
* In chess a queen attacks other squares on the same row, column, or either diagonal as itself.
* So the n-queens problem is to find a set of n*n locations on a chessboard, no two of which
* are on the same row, column or diagonal.
*/
#include "queens.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "../config.h"
#include "../constraints/all_different.h"
//#include "../constraints/fake_all_different.h"
#include "../constraints/minus_ne.h"
#include "../split.h"
#include "../variables.h"
/*
* Solve the n-queens problem with N queens
*/
void run_n_queens(int* csp_dims) {
int n = csp_dims[0];
unsigned long result;
int i, j;
// vector with the IDs of the variables constrained with all_diff
unsigned int* queens = malloc((unsigned int)n * sizeof(unsigned int));
// Create the N Queens variables
for (i = 0; i < n; i++) {
queens[i] = v_new_range(0, (unsigned int)n - 1, true);
}
//c_fake_all_different(queens, n);
c_all_different(queens, (unsigned int)n);
// Create all the minus_ne and ne constraints
for (i = 0; i < n; ++i) {
for (j = i + 1; j < n; ++j) {
c_minus_ne((unsigned int)i, (unsigned int)j, i - j);
c_minus_ne((unsigned int)i, (unsigned int)j, j - i);
}
}
if (FINDING_ONE_SOLUTION) {
printf("\nFinding one solution for n-Queens with %u Queens.\n", n);
} else{
printf("\nCounting all the solutions for n-Queens with %u Queens.\n", n);
}
// Solve the CSP
result = solve_CSP();
if (FINDING_ONE_SOLUTION && result == 1) {
printf("Solution:\n");
vs_print_single_val(queens, (unsigned int)n, 1);
printf("\n");
} else {
printf("%lu solution(s) found\n", result);
}
free(queens);
}