Backtracking algorithm--Summary of Algorithm (IV.)

Source: Internet
Author: User
Tags abs

The backtracking method is also called heuristics, which is a systematic way to search for the solution of the problem. The basic idea of backtracking algorithm is: Go forward from a road, can enter into, can not enter the back, change a road and try again. The general steps to solve this problem using backtracking algorithms are:

1, define a solution space. It includes the solution to the problem.

2, the use of suitable search methods to organize the solution space.

3, the use of depth-first method to search the solution space.

4, use the limit function to avoid moving to the sub-space that cannot produce the solution.

The solution space of the problem is usually generated dynamically in the process of searching the solution of the problem. This is an important feature of the backtracking algorithm.

Classic Sample (post n problem ):

Requires that n queens be placed on a chessboard of n*n to keep them from attacking each other, even if the two queens cannot be placed on the same line or in the same column or on the same slash (a queen in chess can attack any other piece that is in the same row or column or on the same slash).

Note that there are generally a number of possible placement scenarios.

n The Queen's problem is NP-complete. To solve by backtracking method:
(1) Define the solution space of the problem: use n-tuple x[1:n] to represent its solution. That is, a feasible placement scheme. The x[i] indicates that queen I is placed in row I of the chessboard x[i] column. Because it does not agree to put whatever two queens in the same column. So the x[i in the solution vector] are not the same. And no matter what two queens can not put on the same slash is the problem of the implicit constraint. When searching, you can use this slash constraint to cut out invalid subtrees. Consider the chessboard as a two-dimensional square, from the upper left to the lower right corner of the main diagonal and its parallel lines (that is, the slope is 1 of the diagonal),
The difference between the two subscript values of an element is equal.

Similarly, on each slash with a slope of +1, the element's two subscript values are equal.

Therefore, if the two queens are placed in (I,J) and (k,l), and I-j=k-l or I+j=k+l, the two queens are on the same slash. Here the two equations are uniformly represented as |i-k|=|j-l|.
(2) Determine the structure of the solution space tree: The solution space of the N queen problem can be represented by a completely n-fork tree.

The tree branches are labeled with placed column numbers, and the path from the root to the leaf node is a placement scheme. This total n-fork Tree co-owns n**n (n-th-square) leaf nodes, so the algorithm for traversing the spatial tree requires the time complexity of O (n**n).

(3) Search the entire solution space in depth first, and find out the desired solution: The constraint function is Plack (k). It is used to test whether the Queen K placed in the X[k] column is not in the same column as the previously placed K-1 queen. and are not on the same slash. In the backtracking function. If the search reaches the leaf node (i>n). Then a new n-Queen could not attack each other feasible scheme, the number of feasible schemes plus 1.

If the leaf node (i<=n) is not reached, because it is an n-fork tree. The current extension node has n placed column number x[i]=1,2,..., n is represented by the N son node, the Queen I of each column number placement, with the End function place check its feasibility, if feasible, enter the subtree for recursive search, otherwise cut off the sub-tree.

Algorithm implementations such as the following:

The problem and its solution space descriptive narration class queen{private:friend int nqueen (int);  The algorithm implements the function bool place (int k); constraint function void Backtrack (int i);  Backtracking search function int n;  Number of Queens int* X;  Current solution long sum;      Number of viable scenarios currently found};          Constraint function bool Queen::P lace (int k) {for (int j=1;j<k;j++)//infer if Queen K is placed at (K,x[k]), and each previous queen (J,x[j]) is not in the same column and is not on the same slash if ((x[j]==x[k)) | |              (ABS (K-J) ==abs (X[j]-x[k]))      return false;   return true;      } void Queen::backtrack (int i) {if (i>n)//search reaches the leaf node, obtaining a new feasible placement scheme sum++; else//Otherwise the leaf node is not reached.  The current extension node has n column number x[i]=1,2,..., n represents the N son node for (int j=1;j<=n;j++) {x[i]=j;           Place Queen i in column J if (place (i))//If this placement is feasible, then enter this subtree to search recursively Backtrack (i+1);   }}//Algorithm implementation function: Returns the number of possible placement scenarios, where the length of the array x should be n+1.      X[1]~x[n] stored in one of the feasible placement scheme int Nqueen (int* x,int N) {Queen alg;      Alg.n=n;      alg.sum=0;      for (int i=1;i<=n;i++)//Initialize the placement of each queen alg.x[i]=0; Alg. BacktraCK (1);      Search the entire solution space tree delete[] alg.x;   return alg.sum;   }

the time complexity of the algorithm is O (n**n) because of the n**n (n-th) leaf nodes of the solution space tree. The backtracking method has the general problem-solving method called. Because it uses a strategy to search the entire solution space. Backtracking is a powerful tool for some of the most difficult-to-do, combination-number problems, especially for very many NP-complete problems. The retrospective method is effective in organizing the solution space (the structure of tree or graph). The pruning function can also be used to improve the average search efficiency, so its efficiency is much higher than that of pure exhaustive method.


The exam has passed. Occasionally looking back to see, still have a lot of harvest. Looking back at writing these blogs. There may be errors, and there may be some areas that cannot be understood. If there is a problem. Please correct me!

Backtracking algorithm--Summary of Algorithm (IV.)

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: 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.