"Basic algorithm" backtracking and eight queens problem

Source: Internet
Author: User

In chess, the Queen is one of the most powerful pieces that can eat the enemy pieces in the same row, column, and Slash. than the Chinese chess car hundreds of times times stronger than her useless husband is a strong fly (the king can only forward and backward slash to walk a lattice). The tall piece on the right is the queen.

The question of the eight Queens is the question of how many kinds of pendulum do you have to put eight queens on a 8*8 chess board so that every queen cannot eat another queen? This issue in 1848 by the chess player Max Bessel, not only is the year, is almost a year, the 82 Lafite minute by the second of the dregs are not left.

The eight Queens problem is a typical backtracking problem, and we take this problem as an example to introduce the backtracking method.

The so-called backtracking method, the name is tall, the thought is very simple. Imagine putting you in a maze, what is the most direct way to get out of the maze? Yes, try. Choose a road to go up, can not walk back to try another way, not to go back, until you find the exit or all roads have tried to go out so far.

Yes, you're right, this is brute force. For Bigmoyan, who is simply rude and does not like the brain, the blind monk Li Qing said well: if the violence is not to understand the problem, it is meaningless.

Although backtracking is also considered a violent method, it is not particularly violent, and the relevant sectors of special violence are not allowed to sow, and all can be sown with acceptable violence. What do you say? Considering the question of the eight queens, the most violent solution to this problem is this:

The method by which the authorities are not allowed to broadcast:

Choose 8 from the 8*8=64 lattice, put the Queen, test whether meet the conditions, if meet the Count plus 1, otherwise, 8 grid to continue to try.

Obviously, 64 of the 8, not a small number, 1 billion levels of the number of attempts, enough violence.

This is still 8*8 lattice, if change chess chess board ... The picture is so beautiful that I dare not count it.

With a little analysis, we can get a less violent approach, obviously, there can be at most one queen per row per column, and it would be much better if we were to break it down based on that fact. When arranging the Queen, there are 8 methods in the first row, once the first line is selected, assuming (1,i), the second line can only be selected (2,J), where j!=i, so there are 7 kinds of methods. And so on, there are 8 of cases that need to be exhaustive! = 40320 kinds.

It looks like the result is good, but the number of attempts is increased by the factorial level of the problem, and the Bigmoyan is still not satisfied--I might be satisfied! The backtracking is not yet out, if I am satisfied with the rest of the space to say what.

8 Queen too much, the harem is too rich Bigmoyan can hold, as we first cut half analysis to try, so Bigmoyan and 4 queen did divorce formalities, at the same time to reduce the home half, then now the problem becomes 4 queen problem, 4 queen in 4*4 lattice in each arrangement not fight, How many kinds of arrangements are there?

Try to be poor to lift, really need 4! = 24 attempts?

Now we put the first queen in the first lattice, where it is blacked out that the queen cannot be placed.

The Queen of the second row can only be placed in the third or fourth grid, for example, if we put the third lattice, then:

The first two Queens, act evilly, have already locked the third line, and the third Queen can hardly escape the bad luck of being eaten anywhere. So in the case of the first Queen at number 1th, and the second queen at number 3rd, the problem is not solved. We can only go back to the previous step and give Queen number 2nd a place to change.

Obviously, the third Queen has only one position to choose from. When the third Queen occupies the third row of the Blue Vacancy, the fourth row of the Queen has no way to go, so there is an error, return to the upper call (Queen 3rd), and no 3rd can go, continue to return to the upper call (2nd), 2nd has no way to go, continue to return to the upper level (1th), so the queen of

Here, presumably, the reader has a basic idea of the "backtracking" approach. However, the so-called easier, understanding algorithms and writing algorithms is completely different. According to the style of Bigmoyan, the following algorithm analysis, the following code is rewritten from Rujia "algorithm race Primer classic", almost bigmoyan see the implementation of the 8 queen question the most concise code, after rewriting the entire function only 10 lines.

void Queen (int  row) {    if(row==N)        total ++    ; Else         for (int col=0; col!=n;col++) {            C[row]=col;             if (IS_OK (row))                Queen (row+1);        }        }

The algorithm is arranged row by line Queen, whose parameter row is now being executed to the first line. n is the number of Queens, of course, in the eight Queens question is 8.

The 2nd good Understanding, if the program is currently able to execute to line 8th, it is natural to find a solution, so eight Queen problem solution number plus 1.

If the row is not currently in line eighth, the Else statement is entered. Traverse all Columns col, store the current col in array C, and then use IS_OK () to check the row row Col column can put the queen, if you can put the Queen, then recursive call Queen to arrange the next column of the Queen's problem.

Not too clear? Slow down, just at the beginning of the row=0, meaning to the No. 0 line to put the Queen.

If judgment fails, go to else, enter for Loop, col initialized to 0

Obviously, the position of the 0 row 0 column must be able to put the Queen, because this is the first Queen Ah, the harem empty she wants how to toss, so IS_OK (0) test succeeds, recursive call Queen (1) Arranges the Queen question of line 1th.

The 1th line row=1, come in if still test failed, enter for Loop, col initialized to 0. 1 Rows 0 Columns It is obvious that the Queen cannot be placed, because 0 rows and 0 columns already have a mother-of-the-lady in the place, so the IS_OK () test fails, the loop does nothing to spin a circle, Col becomes 1. 1 rows and 1 columns still IS_OK () test failed, until 1 rows 2 columns, found can be placed Queen, so continue to recursive Queen (2) to arrange the second queen position.

What if, in some cases, the problem is not solved? For example, in the 4 Queen's question, 0 rows and 0 columns of the pendulum queen are non-solvable. Assuming the front recursion to Queen (2), found that there is no place on the 2nd row queen, then how to do? Note that the call to Queen (2) is within the For loop frame of the Queen (1), Queen (2) If there is no solution, then naturally Queen (1) of the For Loop Col Self 1, the 1th row of the Queen from 1 row 2 column to 1 row 3 column position, Check if you can put the Queen on the next line of the Queen. So recursion, when the col of Queen (0) is added to 7, the first column of the Queen has traversed from 0 rows 1 columns to 0 rows of 7 columns, when the For loop ends and the program exits.

Call Queen (0) in the main function to get the correct result, 8 queen problem A total of 92 solutions.

All programs are as follows:

1#include <iostream>2#include <math.h>3 using namespacestd;4 5 intn=8;6 intTotal=0;7 int*c=New int(n);8 9 BOOLIS_OK (introw) {Ten      for(intj=0; j!=row;j++){ One         if(C[row]==c[j] | | row-c[row]==j-c[j] | | row+c[row]==j+C[j]) A             return false; -     } -     return true; the } -  - voidQueenintrow) { -     if(row==N) +total++; -     Else +          for(intCol=0; col!=n;col++){ Ac[row]=Col; at             if(IS_OK (row)) -Queen (row+1); -         }        - } -  - intMain () { inQueen0); -cout<<Total ; to     return 1; + } -  

"Basic algorithm" backtracking and eight queens problem

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.