Queen n's explanation and code implementation/C ++

Source: Internet
Author: User

Original Intention

This semester has startedAlgorithmClass, which requires several key algorithm ideasCode. At that time, I felt that I was still able to learn and made serious notes. When I actually write code, I found that

Not fully mastered. The information on the internet is scattered and incomplete, resulting in many detours. After successfully accepting the experiment tonight, I feel that I have gained a lot.

I decided to record the detailed idea of algorithm implementation. I sat down and summarized myself. I also hoped to provide some help to the students who wanted to share the information with me and engage in algorithms.

In this case, I will describe the problem as much as possible.

This blog post focuses on Queen n's issues, plus backpacking issues (Dynamic Planning and branch boundaries) and traveling salesman issues.

 

Preface

No matter what the problem is, it can be abstract. For any problem, you can always find several points that play a decisive role in the overall problem.Internal Relationship between them;

Another important way is to find a special case: for a problem that cannot be started, you can give a few examples to find a special case. Through several key points and special cases, you can easily find the hidden

The essence behind the question.

Here I will give the analysis process of this problem, instead of using mature theories to explain the problem. If you only want code, you can copy it directly.

 

Problem description:

An N * n board should contain N queens. Rule: if the queen isSame Column, same row, same diagonal lineThey attack each other. That is to say, any two queens on the board

Cannot beSame Column, same row, same diagonal line.

 

Problem Analysis

When N is not large, we can use the exhaustive method to solve this problem. For Queen N, each row can be placed in N locations, N rows in total. There will be n n cases. For these cases1. Determine whether the conditions are met.

In fact, a key point is: when can we determine whether the Queen's board meets the conditions? There are two types:

1. Wait for N queens on the board to judge

2. Let a queen judge a specific time. If this situation does not meet the conditions, the situation generated based on this situation will no longer need to be judged, neither of them meets the conditions.

For example, if there is a conflict between the first two rows, no matter how you put them in the backend, there will always be a conflict.

For example:

 

 

Note: This is an illustration of the four queens. Each layer of the tree corresponds to a layer of the Board. The number on the side of the tree represents the position on the board. For example, the number on the side is 3, the location of the Queen in the next row.

Is the third line, and so on. We can see that there are four children in the first line. This is because there is no queen on the board, so every position in the first line can be placed without conflict.

In the second row, there are only three children. At this time, the first row has a queen. To ensure that there is no conflict with the first row, the choice will become smaller. And so on.

If all the situations are considered, each node should have four children, and then judge whether the final situation meets the conditions. This will take more frequent judgments, resulting in inefficiency.

 

The above two embedding methods can lead to completely different algorithm efficiency:

Method 1 judges every situation, which is actually an exhaustive method. Method 2: only part of the situation is determined. For those situations that do not have judgment, it is because we already know that they cannot be resolved.

No judgment is necessary, which can save a lot of time.

(If you are a little professional, you can determine whether the current status meets the conditions in each step when traversing the solution space in depth first. If it does not meet the conditions, you will not continue to traverse the space, but will trace back)

 

So the idea can be like this: Put a queen in the first line (which can be any location), and then find a feasible location in the second line, on this basis, find a location without conflict in the third line. If

If you find that a row has no place to store, modify the previous line (find another location without conflict) and continue traversing. (Backtracking)

What kind of data structure should be used to store the results:

Of course, you can use a two-dimensional array to store it. It is equivalent to simulating a chessboard, storing 1 in the position of the Queen, and 0 in the position of the Queen,

Most of the practices are to store an array (one-dimensional array), which will be described below.

 

Algorithm Implementation

With the above analysis, the algorithm should be better understood.

Recursive and non-recursive solutions are available:

Non-recursive algorithms:

Nqueens1 ( Int N)
{ Int K, n; Extern Int X [N]; k = 0 ; X [k] =- 1 ;
While (K> = 0 )
{X [k] = x [k] + 1 ;
While (X [k] <n )&&(! Place (k) x [k] = x [k] + 1 ; // If the current column does not meet the requirements, the next column is determined.
If (X [k] <n) // exit the while loop if the second condition in the while clause does not meet the preceding conditions, that is, the position that can be placed is found.
{ If (K <n- 1 ) {K = K + 1 ; X [k] =- 1 ;} // Determine whether the current row is the last line. If it is the last line, the result is found and the result is printed.
Else Printf (X [ 0 : N- 1 ]);
}
Else K = k- 1 ; // The while loop is exited because the first condition is not met in the above text. If the column in this row does not meet the condition, return to the previous row and reselect to meet the condition.
 
// Condition column (backtracking)
}
}

Code Description: k indicates the number of rows, and the value of array element x [k] indicates the Queen position of row K. For example, X [3] = 2 indicates that the location of the queen of row 3rd is 2.

Place () is a function used to determine whether the current position meets the conditions. If the conditions are met, true is returned and false is not met. We can see from the loop that, if the current position is not feasible, we can determine the next column: X [k] = x [k] + 1. This function is used in recursion and non-recursion, as mentioned below.

Some people may notice that the initial value of X [k] is-1, because for each rowProgramIt must be determined from the first position (the first column). If it is not satisfied, the processing of each column

Is from the first while loop, X [k] = x [k] + 1 in it, so that the first column is determined for the first time.

Recursive Algorithm:

Nqueens2 ( Int K)
{ Extern Int X [N];
X [k] =- 1 ;
While ( 1 )
{X [k] = x [k] + 1 ;
While (X [k] <n )&&(! Place (k) x [k] = x [k] + 1 ;
If (X [k] <n)
{ If (K <n- 1 ) Nqueens2 (K + 1 ); // If the final solution is not found, the algorithm is called recursively to determine the next row (k + 1)
Else Printf (X [ 0 : N- 1 ]);
}
Else Return ;
}
}

 

For the place () function used in both functions:

IntPlace (IntK)
{IntI;Extern IntX [N];
For(I =0; I <k-1; I ++)
If(X [I] = x [k-1]) | (ABS (X [I]-X [k-1]) = ABS (I-K +1)))
Return False=0;
Return True=1;
}

The input parameter is K (number of rows), and array X [N] is introduced, so that you can know the location of the queen from the first row to the K row, (As mentioned above, the array X [k] stores the Queen's location)

To determine whether the X [k] column of the K row meets the condition, as long as each row before K is used to compare with it, as long as one row does not meet the condition, false is returned.

(X [I] = x [k-1]) Indicates that they are in the same column,(ABS (X [I]-X [k-1]) = ABS (I-K +1) Indicates that they are on the same diagonal line.


Algorithm Implementation Code (Recursive Implementation)

 

# Include <fstream>
# Include <iostream>

STD: ofstream fout ( " Queenoo.txt " );

/**//* Record the current placement scheme */
Int * X;
/**//* Number of Queens N and number of solutions */
Int N, sum = 0 ;
/**//* Check whether the Queen Placement Scheme indicated by the parameter meets the requirements */
Int Place ( Int );
/**//* Recursive Method for Queen placement */
Void Queen1 ( Void );
/**//* Recursive Method for obtaining the Queen's placement scheme */
Void Traceback ( Int );
/**//* Print the current placement plan */
Void Printmethod ( Void );

Int Main ()
{
Using Namespace STD;
Long Start, stop;
Cout < " Input N number of input Queens: " ;
Cin> N;

X = ( Int *) Malloc ( Sizeof ( Int ) * N );
Time (& START ); /**//* Record Start Time */
Queen1 ();
Time (& stop ); /**//* Record End Time */
Cout < " The total number of solutions is: " <Sum < " \ N " ;
Cout < " Total time spent: " <( Int (Stop-start) < " \ N " ;
Fout < " The total number of solutions is: " <Sum < " \ N " ;
Fout <cout <" Total time spent: " <(Stop-start) < " \ N " ;

}

Int Place ( Int R)
{
Int I;
For (I = 0 ; I <r; I ++ ){
If (X [R] = x [I] | ABS (r-I) = ABS (X [R]-X [I])
Return 0 ;
}
Return 1 ;
}

Void Traceback ( Int R)
{
Int I;
If (R> = N ){
Printmethod ();
Sum ++;
/**//* Printmethod (); */
} Else {
For (I = 0 ; I <n; I ++ ){
X [R] = I;
If (Place (R) traceback (R + 1 );
}
}
}

Void Printmethod ( Void )
{
Int I, J;
STD: cout < " The " <Sum < " Solution \ n " ;
Fout < " The " <Sum < " Solution \ n " ;
For (I = 0 ; I <n; I ++ ){
For (J = 0 ; J <n; j ++ ){
If (J = x [I]) STD: cout < " 1 " , Fout < " 1 " ;
Else STD: cout < " 0 " , Fout < " 0 " ;
}
STD: cout < " \ N " ;
Fout < " \ N " ;
}
}

Void Queen1 (Void )
{
Traceback ( 0 );
}

The above code cfree5 is compiled.

The Code inputs the experiment result to the file"In queenoo.txt, the path is in the compiler installation path, and the Execution Code is located in the same directory.

Non-recursive code is similar, so it is not written.


Postscript

The solution to the eight queens problem is a method called backtracking. This idea is embodied in the above analysis process, and the judgment is added when the depth first traverses the solution space.

Condition. The traversal continues only when the condition is met. The production of any theory involves the practice first. The theory can be summarized only when the practice is correct.

However, many algorithm books now provide internal theories and give examples. In fact, this is not a good learning method. In this case, the intermediate learner lacks much of the process of thinking and derivation.

It is the prototype of the theory. Ignoring this key role, we just passively accept the idea of the algorithm and do not know how the algorithm is generated. We do not know where it is, so it is natural to learn it.

Not thorough and difficult to grasp.

So when talking about the Queen's question, I didn't start to talk about the Backtracking Method, the Backtracking Method, and how to use the Backtracking Method. Instead, we use our original thinking to think about how to solve the problem,

This is the Backtracking Method. At that time, the study of theory can deepen the understanding of algorithm ideas, and it will be better if you are thinking and analyzing it yourself.

Master algorithms.


 

If any of the above blog posts is incorrect, I hope you can correct them. Thank you very much.


The backtracking method mentioned above will be described in the next blog.


If there is reprint please indicate the source: http://www.cnblogs.com/yanlingyin/

A fish @ blog garden 2011-12-19

 

 

 

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.