Author: Leen Ammeraal
Date: 02:45:28 01/18/03
Go up one level in this thread
Below is a solution (in C) to the 8-queens problem, very close to
the one I wrote in a book about 15 years ago.
Leen
/* queen8.c: Solution to the 8-queens problem, Leen Ammeraal.
*/
#include <stdio.h>
#include <stdlib.h>
#define N 8
int count=0;
int a[N+1];
int valid(int k, int j)
{ int h;
for (h=1; h<k; ++h)
if (a[h] == j || abs(j - a[h]) == k - h)
return 0;
return 1;
}
void fillRemainingFiles(int m)
/* The files 1, 2, ..., m are already OK */
{ if (m == N)
{ int k;
for(k=1; k<=N; ++k)
printf(" %2d", a[k]);
printf("\n");
++count;
}
else
{ int k=m+1, j;
for (j=1; j<=N; ++j)
if (valid(k, j))
{ a[k] = j;
fillRemainingFiles(k);
}
}
}
int main()
{ fillRemainingFiles(0);
printf("There are %d solutions.\n", count);
return 0;
}
This page took 0 seconds to execute
Last modified: Thu, 15 Apr 21 08:11:13 -0700
Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.