"Recursion" in data structures and algorithms -- solving the eight queens Problem Using backtracking

Source: Internet
Author: User

The eight queens issue is an ancient and famous issue. It is a typical example of backtracking algorithms. This problem was raised by the famous German mathematician Gauss in the 19th century in 1850: Eight queens were placed on the 8-row, 8-column chess board. If the two queens are on the same row, the same column, or the same diagonal line, they are known as mutual attacks. In chess, the Queen is the most powerful piece because it has the largest attack range. Figure 6-15 shows a queen's attack range.



Figure 6-15 Queen's attack Scope
These eight queens cannot attack each other, that is, they cannot be in the same row, in the same column, or in the same diagonal line. Gaussian believes there are 76 solutions. In 1854, different authors published 40 different solutions in the Berlin chess magazine. Later, they used Graph Theory to solve 92 solutions. In modern teaching, the eight queens problem is considered as a typical recursive algorithm example. Figure 6-16 shows two cases where eight queens do not attack each other.

Figure 6-16 no mutual attacks by eight queens
Now let's take a look at how to use the Backtracking Method to Solve the eight queens problem. This algorithm will place the queen in a column on the board until the eight queens are placed on the board without mutual attacks, and the algorithm ends. When a new queen is attacked by an existing queen and cannot be placed on the board, the algorithm goes back. Once this happens, we try to move the queen that was last placed on the board to another place. This is to enable the newly added queen to be placed in the proper position of the Board without being attacked by other queens. As shown in Figure 6-17, although the 7th queens won't launch attacks against any queen on the board, they still need to be removed and traced back, because it is impossible to find a proper position on the board for the 8th queens.

Figure 6-17 backtracing
The backtracking part of the algorithm will try to move the 7th queens to the other point in the 7th column to find a suitable position for the 8th queens in the 8th column. If the 7th queens cannot be moved because they cannot find a proper position in the 7th columns, the algorithm must remove it and then trace back to the queen of the 6th columns. The final algorithm repeats the process of placing the Queen and tracing until the problem is solved.
The following is an example program for solving the eight queens problem.
# Include <conio. h>
# Include <iostream>

Using namespace STD;
// First, the queen should not conflict, so there should be only one queen in each line
// Use the queens [] array to store the location of each queen
// For example, Queens [m] = n indicates that the Queen of Row M is placed on column N.

# Define Max 8

Int sum = 0;
Class queenpuzzle
{
Int queens [Max]; // stores the column label of the queen of each row
 
Public:
Void printout (); // print the result
Int isvalid (int n); // determines whether the nth queen is valid after it is put.
Void placequeen (int I); // recursive algorithm placement queen
};

Void queenpuzzle: printout ()
{
For (INT I = 0; I <Max; I ++)
{
For (Int J = 0; j <Max; j ++)
{
If (j = queens [I])
Cout <"Q ";
Else
Cout <"0 ";
}
Cout <Endl;
}
Cout <Endl <"press the Q keyboard to exit and press another key to continue" <Endl;
 
If (getch () = 'q ')
Exit (0 );
}

// Place the Queen in line I
Void queenpuzzle: placequeen (int I)
{
For (Int J = 0; j <Max; j ++)
{
// If all the output results are complete
If (I = max)
{
Sum ++;
Cout <"nth" <sum <"group solution:" <Endl;
Printout ();

Return;
}

// Place the queen
Queens [I] = J;

// This location cannot be used by the Queen to continue the test.
If (isvalid (I ))
Placequeen (I + 1 );
}
}

// Determine whether the nth queen is legal after it is put, that is, whether there is no conflict
Int queenpuzzle: isvalid (int n)
{
// Compare the positions of the n-th queen with those of the n-th queen.
For (INT I = 0; I <n; I ++)
{
// The two queens are in the same column and 0 is returned.
If (Queens [I] = queens [N])
Return 0;

// The two queens are on the same diagonal line and return 0
If (ABS (Queens [I]-Queens [N]) = (n-I ))
Return 0;
}

// If no conflict exists, return 1.
Return 1;
}

Void main ()
{
Queenpuzzle queen;
Queen. placequeen (0 );
Cout <"Total" <sum <"group solution" <Endl;
}


Because the backtracking method is also trying to search for all possible options in the whole solution space, some people may mistakenly think that the backtracking method is similar to the exhaustive method, but in fact the backtracking method is much more efficient than the exhaustive method. Here we will use a simple estimation method to analyze the eight queens problem. First, we use the exhaustive method to calculate that the total number of nodes in the solution space of the problem is 109601. Then, 20 paths are randomly selected based on the backtracing method to estimate the number of nodes and obtain the average value of the total number. Because 92 solutions are known to the eight queens problem, the results obtained by selecting 20 random paths can be closer to the actual values. After calculation, the average number of knots produced by the Backtracking Method is about 1740, which is less than 109601 compared with 2%, it can be seen that the backtracking method is highly efficient as a method that combines leaping and systematic search.

The above content is excerpted fromC ++ data structure principles and typical problem solvingSection 6.3.3 is published by the Electronic Industry Publishing House.

Chapter 2 Recursion
6.1 concept of Recursion
6.1.1 Definition
6.1.2 apply recursion principles
6.1.3 recursive and non-recursive Conversions
6.2 division and Control Law
6.2.1 Summary of the divide and conquer Law
6.2.2 tower Problems
6.2.3 infectious disease problems
6.3 backtracking
6.3.1 Brief description of Backtracking Method
6.3.2 maze Problems
6.3.3 queen of eight
6.3.4 about Knight's travel
6.4 summary of this Chapter

 

 

========================================================

If you want to communicate with me, welcome to the link http://student.csdn.net/invite.php? U = 113322 & C = a139a65a1494291d and I became friends!

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.