#include<stdio.h>
#include<conio.h>
int queen[55],sols;
int place(int,int);
int abs(int);
void n_queens(int k,int n)
{
int r,w,i,j;
static int l=1;
for(i=1;i<=n;i++)
{
if(place(k,i)==1)
{
queen[k]=i;
if(k==n)
{
if(l==1)
{
printf("Pictorial solution to %d QUEENS PROBLEM:\n",n);
l++;
for(r=1;r<=n;r++)
{
for(w=1;w<=n;w++)
{
if(w!=queen[r]) printf(" *");
else printf(" Q");
}
printf("\n");
}
//printf("Other solutions:\n");
}
//for(j=1;j<=n;j++) printf(" %d",queen[j]);
//printf("\n");
sols++;
}
else n_queens(k+1,n);
}
}
}
int place(int k,int i)
{
int j;
for(j=1;j<k;j++)
{
if((queen[j]==i)||((abs(queen[j]-i))==(abs(j-k))))
{
return 0;
}
}
return 1;
}
int abs(int x)
{
if(x<0) return (-x);
else return x;
}
int main()
{
int num;
printf("\t\t\t\tN - QUEENS PROBLEM\n\n");
printf("Enter the no. of queens: ");
scanf("%d",&num);
printf("\n\tAll possible placements of %d queens\n\n",num);
n_queens(1,num);
printf("\nTotal number of solutions: %d",sols);
return 0;
}
/*input:14 15 output:365596 22791848*/
############################################################
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define NMAX 130
#define MAXCANDIDATES 130
int solution_count;
void construct_candidates ( int a[], int k, int n, int c[], int *ncandidates )
{
int i,j ; /* counter */
bool legal_move ; /* who is in the permutation? */
*ncandidates = 0;
for ( i = 1; i <= n; i++ )
{
legal_move = true;
for(j=1;j<k;j++)
{
if(abs(k - j) == abs(i - a[j]))
legal_move = false;
if(i == a[j]) legal_move = false;
}
if ( legal_move == true )
{
c[ (*ncandidates)++] = i ;
}
}
return ;
}
bool is_a_solution ( int k, int n )
{
return ( k == n ) ;
}
void process_solution( int a[], int k )
{
int i; /* counter */
/*for ( i = 1; i <= k; i++ )
printf ( "%c", s[ a[i] - 1 ] ) ;
printf("\n");*/
solution_count++;
return ;
}
/*
int sort ( const void *a, const void *b )
{
char *x, *y, c, d ;
x = ( char * ) a ;
y = ( char * ) b ;
c = tolower (*x) ;
d = tolower (*y) ;
if ( c == d ) return ( *x - *y ) ;
return ( c - d ) ;
}*/
void backtrack ( int a[], int k, int n )
{
int c[MAXCANDIDATES] ; /* candidates for next position */
int ncandidates ; /* next position candidate count */
int i ; /* counter */
if ( is_a_solution ( k, n ) ) // is k == n
process_solution ( a, k ) ;
else
{
k = k + 1 ;
construct_candidates ( a, k, n, c, &ncandidates ) ;
for ( i = 0; i < ncandidates; i++ )
{
a[k] = c[i] ;
backtrack ( a, k, n);
}
}
return ;
}
void generate_permutations ( int n )
{
int a[NMAX] ; /* solution vector */
solution_count = 0;
backtrack ( a, 0, n) ;
printf("n = %d solution_count = %d\n",n,solution_count);
return ;
}
int main ()
{
int len, N,n;
//freopen ( "195.in", "r", stdin ) ;
//freopen ( "195.out", "w", stdout ) ;
scanf ( "%d", &N ) ;
while ( N-- )
{
scanf ( "%d", &n ) ;
//qsort ( s, len , sizeof ( char ), sort ) ;
//printf ( "%s\n", s ) ;
generate_permutations ( n ) ;
}
}
/*input:14 15 output:365596 22791848*/
No comments:
Post a Comment