[DFS + N Queens backtracking]

description

  N * N is placed on the board without the N queens attack each other (i.e., any line in the board, and any one can not place any two queens on a diagonal line), all programming solver

Display method.

Entry

  A number N (3 <= N <= 10) is the N * N represents the board size.

Export

  Output program number; if no program, the output "no solute!"

Sample input 1 

4

Sample Output 1

 
   
2

Problem-solving ideas
  This is a classic subject of a retrospective search. First of all, we each put a mark Queen gave the column marked (because we are put Queen line by line, so to ensure the uniqueness of the line),
we found that each of the two diagonal Queens control, then each have a diagonal to satisfy such a characteristic: plus either equal ordinate abscissa, ordinate or abscissa Save equal coordinates. The
order to open the two arrays is determined.
answer
. 1 #include <bits / STDC ++ H.>
 2  the using  namespace STD;
 . 3  int n-, NUM = 0 ;
 . 4  BOOL L [ 10001 ]; // tag for each column
 . 5  BOOL X [ 10001 ]; // add abscissa ordinate
 . 6  BOOL Y [ 10001 ]; // Save ordinate abscissa coordinate
 . 7  BOOL MP [ 10001 ] [ 10001 ]; // map (output convenient)
 . 8  void Queen ( int ANS)
 . 9  {
 10      IF (n-ANS == + . 1 ) / / Queen If eight plus a program to put over
 11      {
12 is          NUM ++ ;
 13 is          
14          return ;
 15      }
 16      for ( int J = . 1 ; J <= n-; J ++ )
 . 17      {
 18 is          IF (!!! L [J] && X [ANS-J] && Y [ANS + J]) // If the queen put no conflict
 . 19          {
 20 is              L [J] = to true ;
 21 is              X [ANS-J] = to true ;
 22 is              Y [J ANS +] = to true ;
 23 is              MP [ANS] [J] = to true ; // marking
 24-              Queen (ANS + 1); // put a queen
 25              L [J] = to false ;
 26 is              X [ANS-J] = to false ;
 27              Y [J ANS +] = to false ;
 28              MP [ANS] [J] = to false ; // unmark (back)
 29          }
 30      }
 31 is      return ;
 32  }
 33 is  int main ()
 34 is  {
 35      CIN >> n-;
 36      Queen ( . 1 );
 37 [      COUT << NUM;
 38 is      return  0 ;
 39 }

 

 

Guess you like

Origin www.cnblogs.com/hualian/p/11031988.html