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 for solving problems with backtracking algorithms are:

1, define a solution space, it contains the solution of 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, which is an important feature of backtracking algorithm.

      Classic example (n problem ):

Requires that n queens be placed on a chessboard of n*n to keep them from attacking each other, even if any 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 There are often a number of possible placement scenarios.
The N Queen problem is NP-complete and is solved by backtracking:
(1) Define the solution space of the problem: use n-tuple x[1:n] to express its solution, that is, a feasible placement scheme. Where X[i] indicates that queen I is placed on the X[i] column of the chessboard. Because no two queens are allowed to be placed in the same column, the x[i in the solution vector are different. And any 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: You can use a complete n-fork tree to represent the solution space of the N queen problem. 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 has a n**n (n-th-square) leaf node, 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, find out the 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 is not on the same slash. In the backtracking function, if the search reaches the leaf node (i>n), it is possible to get a new n-Queen without attacking, and the number of feasible schemes is 1. If you have not reached the leaf node (i<=n), because it is a n-fork tree, the current expansion node has n placed column number x[i]=1,2,..., n represents the N son node, the Queen I of each column number placement, with the End Function place to check its feasibility, If feasible, enter this subtree for recursive search, otherwise cut off the subtree. The algorithm is implemented as follows:

The problem and its solution Space description 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++)//Judging 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 did not reach the leaf node, the current expansion 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: Return the number of feasible placement scheme, 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 is the search for the entire solution space strategy, for some do not know, the combination of large number of problems (especially many NP complete problems), backtracking is a powerful tool. The retrospective method effectively organizes the solution space (the structure of the tree or graph), and can use the pruning function to improve the average search efficiency, so its efficiency is much higher than the pure exhaustive method.


Although the examination has passed, occasionally looking back to see, there is a lot of harvest. Remember to write these blogs, there may be errors, there may be some understanding of the place, 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.