Cod sursa(job #2437143)

Utilizator stratonedanielDaniel Stratone stratonedaniel Data 8 iulie 2019 17:07:21
Problema Problema Damelor Scor 90
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>

#define maxQueens 100

typedef struct coords{

	int X, Y;

}Coords;

int factorial = 1;
int N;
int number_of_solutions = 0;
int queens[maxQueens];
FILE *read, *write;

bool goodSolution(int step)
{
	if (step == N - 1)
	{
		number_of_solutions ++;
		return true;
	}
	return false;
}

bool goodQueen(int step)
{

	for (int i = 0; i < step; i++)
	{

		if (queens[i] == queens[step] || 
			(abs(i - step) == abs(queens[i] - queens[step])))
			return false;
	}

	return true;
}

void print()
{
	
	for (int i = 0; i < N; i++)
	{
		factorial *= (i + 1);

		if (i != N - 1)
			fprintf(write, "%d ", queens[i]);
		else 
			fprintf(write, "%d\n", queens[i]);
	}
}

void back(int step)
{
	if (step > N)
		return;

	for (int i = 1; i <= N; i++)	
	{	
			queens[step] = i;
			
			if (goodQueen(step) == true)
			{
					if (goodSolution(step) == true)
					{
						if (number_of_solutions == 1)
							print();
					}
					else
						back(step + 1);	
			}
	}

}



int main()
{
	read = (FILE *) fopen("damesah.in", "r");
	write = (FILE *) fopen("damesah.out", "w");

	fscanf(read, "%d", &N);

	back(0);

	fprintf(write, "%d\n", number_of_solutions);

	fclose(read);
	fclose(write);

	return 0;
}