A simple understanding of the eight queens problem of backtracking

Source: Internet
Author: User

backtracking , a simple understanding is the active traceability. The basic idea to learn from the poor lifting method, but it is not blindly, when found that a step does not meet the conditions, this step behind the poor lifting operation is not carried out (commonly known as "pruning"), I call it dynamic poor lifting method. Assuming the first step is feasible, then perform the second step, the third one ... If the third step does not work, then we come back (backtracking), the second step in a different way to try, and then re-third step, fourth ... Until the task is completed.

Here, take the eight queen question as an example. Try to make the backtracking clear.

Note: Recursion should be an algorithmic structure, and backtracking is an algorithmic idea.

What is the eight Queen's question?

(Baidu Encyclopedia) Eight Queen's question is a chess-based question: how can you place eight queens on an 8x8 chess board so that no queen can directly eat the rest of the queen? To achieve this, neither of the two queens can be in the same row, vertical line, or slash. The eight Queens question can be generalized to a more general N Queen placement problem: The size of the board becomes NXN, and the number of Queens becomes N. The problem has a solution when and only if n = 1 or n≥4.

The eight Queens issue was first introduced by the international chess player Max Bessel in 1848. Later, mathematicians studied them, including Gauss and Cantor, and promoted them to the more general problem of placing n queens. The first solution to the eight Queens question was given by Franz Nock in 1850. It is also one of the first to generalize the problem to a more general N-Queens placement problem. In 1874, S. Gandre proposed a method that was solved by determinant, and this method was later improved by J.W.L. Glaisher.

Edsger Dijkstra used this problem as an example in 1972 to illustrate his ability to call structural programming. The eight Queens problem appeared in the seventh visitor of the famous video game in the early 1990 's.

Thinking of solving problems

We use backtracking to solve this problem. Remember what I said about dynamic poor lifting ("pruning")? Then we'll start to be poor. Please look at the process. Eight queens, each queen put a line, so we have to make sure that the queen of each row to put the position of the column. For the first row, suppose you put the Queen in the first column (A For loop starts here). The first step is certainly satisfying, then we look at the second line (and start A For loop again), assuming that the second queen is placed (2,1) (Row, column), not ("pruning")! Then keep for, put in (2,2), no ("pruning")! Continue for, place at (2,3). Bingo! then we take the third step, the fourth step .... Perhaps, in the third step, after performing the eight for loop of the third step, there is still no reasonable answer. Then we have to go back to the second step. At this time, put the second queen in (2,4). Go on......

(Refer to http://blog.csdn.net/justme0/article/details/7540425)

Next, we're going to try to turn this process into pseudo-code.

//find out which column the queen of the current line should be invoidFindqueen (row) { for(intI=0;i<8; i++) {//1. Determine whether the current requirements are met      if(Is_meet (row,i)) {//2. Determine if the current is the last line        if(last line) {output operation, and return}//3. Perform the next line matchFindqueen (row+1); //4. If you go to this step, the step three is finished, there is no suitable result, you need to return to the previous step, that is, the next loop to execute the current for       }}}

Determine if the condition is met

Here, there is a step we need to consider again, that is, the 1th step, how to judge the current insertion of the Queen satisfies the condition.

According to the rules of chess, there cannot be two queens located in: 1) the same column; 2) the same diagonal.

1) Same column

Better judgment, the same column number, that is, belong to the same column;

2) Same Diagonal

There are two types of positions: forward diagonal and backslash. The judging conditions are: (r1+c1) = = (R2+C2), (r1-c1) = = (R2-C2)

Compare the new Queen's position to the Queen's position that has been inserted in turn.

Specific implementation

See the above code, you should have a little idea. Implement the Code on the specific implementation.

BOOLIs_meet (intRowintcolumn) {    intC;  for(intR=0; r<row;r++) {C=Queen[r]; if(column==c)return 0; if((row+column) = = (c+R))return 0; if(column-row) = = (C-R))return 0; }    return 1;}voidFindqueen (introw) {     for(intC=0;c<8; C + +)    {        if(Is_meet (row,c)) {Queen[row]=C; if(row==7) {print (); return; } findqueen (Row+1); } Queen[row]=-1; }}

For fun, simply change it so that it can display the matching process dynamically in the console.

#include"iostream"#include"string"#include<Windows.h>using namespacestd;intqueen[8];voidprint () {System ("CLS"); cout<<"Eight Queen's question dynamic demo \ n"; cout<<"------------------------\ n";  for(intOuter =0; Outer <8; outer++)    {        if(queen[outer]!=-1)        {         for(intInner =0; Inner < Queen[outer]; inner++) cout<<" . "; cout<<" # "; }         for(intInner = Queen[outer] +1; Inner <8; inner++) cout<<" . "; cout<<Endl; }}BOOLIs_meet (intRowintcolumn) {    intC;  for(intR=0; r<row;r++) {C=Queen[r]; if(column==c)return 0; if((row+column) = = (c+R))return 0; if(column-row) = = (C-R))return 0; }    return 1;}voidFindqueen (introw) {     for(intC=0;c<8; C + +) {Sleep ( +);        Print (); if(Is_meet (row,c)) {Queen[row]=C; if(row==7)            {                //print ();                return; } findqueen (Row+1); } Queen[row]=-1; }}intMain () {memset (Queen,-1,8*sizeof(int) ;//Here is the assignment-1, so it's not going to go wrong, so be clear memset is the assignment of a single byte in turn Findqueen (0);}

A simple understanding of the eight queens problem of backtracking

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.