Recursive solution to the eight queens problem

Source: Internet
Author: User

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 );

}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.