Recursive algorithms for the eight queens problem
# Include <stdio. h>
# Include <stdlib. h>
# Define N 8/* board side length */
# Define XXN 15/* number of positive (inverse) diagonal lines */
# Define TRUE 1
# Define FALSE 0
Int map [N] [N];/* board */
Int col [N];/* column */
Int XX [XXN];/* diagonal line */
Int YY [XXN];/* diagonal line */
FILE * fp;
Int num = 0;/* Number of solutions */
/**
Show a solution
*/
Void showMap ()
{
Int I, j;
Fprintf (fp, "n -------------------------- n ");
For (I = 0; I <N; I ++ ){
For (j = 0; j <N; j ++)
Fprintf (fp, "%-3d", map [I] [j]);
Fprintf (fp, "n ");
}
}
/**
Recursive function
*/
Int try (int y)
{
Int I, j;
Int success = FALSE;
If (y = N) {/* find a solution */
ShowMap ();
Num ++;
Return TRUE;
}
For (I = 0; I <N; I ++ ){
If (XX [N-y + I] = 0 & YY [I + y] = 0 & col [I] = 0)/* ensure layout requirements; diagonal lines, columns, no duplicate pawns */
{
XX [N-y + I] = YY [I + y] = col [I] = map [y] [I] = 1;
If (try (y + 1) success = TRUE;/* put the next Queen */
XX [N-y + I] = YY [I + y] = col [I] = map [y] [I] = 0;
}
}
Return success;
}
Main ()
{
Int I, j, result;
Fp = fopen ("queen8.txt", "w + ");
For (I = 0; I <N; I ++)
For (j = 0; j <N; j ++)
Map [I] [j] = 0;
For (I = 0; I <XXN; I ++) XX [I] = YY [I] = 0;
Fprintf (fp, "n start ..............");
If (! Try (0) printf ("n no resolution! ");
Fprintf (fp, "n num = % d", num );
}