queens.c 1.93 KB
/*
 * 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);
}