Backtracking method and N-Queen Problem _ backtracking method

Source: Internet
Author: User
Tags abs

Reference

Http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html

Http://www.cnblogs.com/Creator/archive/2011/05/20/2052341.html 1, what is backtracking method

Backtracking is a method of systematically searching the solution of the problem. Try to find the solution to the problem during the search, and if you can't find it, step back and backtrack (the pruning process). Backtracking can be used for many complex and large-scale problems.
The basic idea of backtracking is to search in depth first, start searching from the root node, when to a node to determine whether it is the solution of the problem, if the inclusion from the node continue to search, if not included, to the parent node backtracking. If we use backtracking to solve all the solution of the problem, we should go back to the root, and all the viable subtrees of the root node must be searched over. If we use backtracking method to find any solution, we can end it by searching a solution of the problem.
The pruning function commonly used in backtracking: (1) Constraint function: Subtract the subtree that does not satisfy the constraint at the node. (2) Boundary function: minus the subtree of the best solution 2, the general steps of the backtracking method to solve the problem, to solve the problem, to determine the solution space using a suitable search method to organize the solution space using the depth-first search solution space use pruning function to avoid invalid search in the search process. 3, the solution of the algorithm frame problem is an n-dimensional vector (a1,a2,........., an), the constraint condition is that the AI (i=1,2,3,....., N) satisfies some condition and is recorded as F (AI). Non-recursive backtracking framework

int a[n], I;
initialization of a[n];
i = 1;
while (i > 0 (there is a road to go) and (did not reach the goal)//no backtracking to the end
{
    if (i > N)
    {
        Search for a solution, output;
    }
    else
    {
        a[i ] The first possible value, while
        (A[i], is the next possible value in {A[i] if it does not meet the constraint and in the search space
            ;
        }
        if (A[i] in search space)
        {
            Identification of resources occupied;
            i = i + 1;  Extend the next node
        }
        else {The
            space state occupied by scavenging;  //backtracking
            i = i-1
}}}
Recursive backtracking framework
int a[n];
Try (int i)
{
    if (i>n)
        output result;
    else
   {for
    (j = lower bound; J <= Upper bound; j=j+1)  //enum I all possible paths
       {
            if (fun (j))                 //satisfy the bounds function and constraints
              { C42/>a[i] = j;
               ...                         Other Operation
                 try (i+1);
              Cleanup before backtracking (such as a[i] null values, etc.);}
              }
 
4 Example: n Queens question

Place n Queens on a n*n chessboard, each row one and make it unable to attack each other (the Queen on the same row, the same column, the same slash will automatically attack).

/* Use n-tuple x[1:n] to represent the solution of the N-post problem. X[i] represents the queen I placed in the first row of the chessboard of the x[i] column */#include <stdio.h> #include <math.h> #include <stdlib.h> static int n, x
[1000];

static long sum;
* To determine whether the K can be placed in the x[k] two queens can not be placed on the unified slash: If the 2 Queens placed positions are (I,J) and (k,l), and i-j = k-L or i+j = K+l, then the 2 queens are in the same slash.
    */void OutPut () {for (int i = 1; I <= n; ++i) printf ("(%d,%d)", I, x[i]);
printf ("\ n");
            int place (int k) {for (int j = 1; j < K; ++j) if (ABS (K-J) = ABS (X[k]-x[j)) | | x[j] = = X[k])
    return 0;
return 1;
        } void BackTrack1 (int t) {//If T>n description has been completed once place if (T > N) {sum++;
    OutPut ();
            else {for (int i = 1; I <= n; ++i) {x[t] = i;
        If place (t)//can be placed at the I position, continue searching for BackTrack1 (t + 1);
    }} void BackTrack () {int k;       X[1] = 0;
    Initialized to 0 k = 1;  while (k >= 1)//loop {X[k] + = 1; First position WHIle ((X[k] <= N) &&! (                      Place (k))//If not X[k] + + + 1; Put in the next position if (X[k] <= N)//place Complete {if (k = = N)//IF                      Have finished n Queen {sum++;
            The number of processing times, output ();
                else//has not finished processing, let K self add, processing next queen {k++;
            X[k] = 0;                            }//x[k] > N, indicating that there is no suitable location for else k--;
    Backtrack back, back to step k-1} int main () {clock_t start, finish;

    Double duration;
    int nn;
        while (scanf_s ("%d", &nn)!= EOF) {n = nn;
        sum = 0;
        for (int i = 0; I <= N; ++i) x[i] = 0;
        BackTrack ();
        BackTrack1 (1);
    printf ("%d\n", sum);
return 0;

 }

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.