Cod sursa(job #2437152)

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

int N;
int number_of_solutions = 0;
int queens[20];
FILE *read, *write;

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 back(int step)
{
	if (step >= N)
		return;

	for (int i = 1; i <= N; i++)	
	{	
			queens[step] = i;
			
			if (goodQueen(step) == true)
			{
					if (step == N - 1)
					{
						number_of_solutions ++;
						if (number_of_solutions == 1)
						{
							for (int i = 0; i < N; i++)
							{
								if (i != N - 1)
									fprintf(write, "%d ", queens[i]);
								else 
									fprintf(write, "%d\n", queens[i]);
							}
						}
					}
					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;
}