Huawei Machine test-N Queen problem (advanced topic 160 points: Two backtracking methods to solve vomiting of blood)

Source: Internet
Author: User

First, the problem description:
Place the N-Queens that are not attacked by each other on the board of the NXN grid. According to the rules of chess, the Queen can attack pieces that are on the same line or in the same column or on the same slash. n the problem is equivalent to placing n queens on the re-NXN board, any 2 queens may be on the same row or column or on the same slash.
Input:
Size of a given checkerboard N (n≤13)
Output:
How many placement methods are available for the output.


Second, the problem-solving ideas:
To solve the problem of N queen, is to solve how to place the N queen, each queen and all the queens in front of the same row, the same column, the same diagonal, where we can take precedence, that is, the Queen's line number in order to increment, only consider the I-Empress placed in row I of which column, So when I put the Empress I can be judged from the 1th column, if it can be placed in the 1th position, then jump to the next line to place the next queen. If not, skip to the next column ... Until the last column, if the last column cannot be placed, indicates that the placement method has an error at this point, and then back to the previous Queen to place the next column. This is where the essence of backtracking is. When the nth queen is successfully placed, a workable solution is obtained, at which point the previous queen is re-placed to find the next viable solution ... After that, you can find all the possible solutions to an N-queen problem.


Third, the complexity of analysis:
About the complexity of the problem of n Queens can be said that there are divergent opinions, I have changed several times, just beginning to think that the chessboard is n row n column, so it should be n^2, and later found in each column selection can be placed on the comparison and did a cycle, so should be n^3, but think for a long time, Found that the decision can be placed not every time the cycle to n, it is based on the value of the Queen I change, so the complexity should be 1/3 n^3 around, that is, less than n^3.


Iv. Test Code:
Two implementation methods, one is recursive backtracking, one is iterative backtracking, the same idea, but the form is different.


Recursive backtracking

#include <stdio.h> #include <math.h>   #define N     int n;//queen number   int sum = 0;//number of possible solutions   int x[n]; Number of columns placed by the Queen *   /* judgment function, determine if the K queen can be placed in a certain position   * If the previous Queen appears in the same column or the same diagonal drop fails, return 0, otherwise return 1  *  /int place (int k)   {       int i;       for (i=1;i<k;i++)         if (ABS (k-i) ==abs (x[k]-x[i]) | | x[k] = = X[i])           return 0;       return 1;   }     /   * Solve a workable solution function, when the T-Queen can be placed in a position in the T line, continue to place the next queen, until   * All queens are placed to the end, if a queen cannot be placed, then move down a column to place, if this column can not be placed   * or all queens placed end , return to the previous Queen to reposition and eventually return the number of all possible solutions.  *  /int Queen (int t)   {       if (t>n)//When the Queen is placed above N, the number of feasible solutions plus 1      sum++;       else        for (int i=1;i<=n;i++)         {             x[t] = i;//Mark T queens placed in column I if (place             (t))//If it can be placed in a certain position, then continue to put down a queen               Queen (t+1);          }       return sum;   }     int main ()   {       int t;       while (~SCANF ("%d", &n)) {   T = Queen (1);   if (n = = 0)//If n=0, then the number of feasible solutions is 0, this case must not ignore     t = 0;   printf ("%d\n", t); sum=0;}    return 0;   


Iterative backtracking

#include <stdio.h> #include <math.h>  #define N     int n;   int sum = 0;   int x[n];     int place (int k)   {       int i;       for (i=1;i<k;i++)         if (ABS (k-i) ==abs (x[k]-x[i]) | | x[k] = = X[i])           return 0;       return 1;   }     int Queen ()   {         x[1] = 0;         int t=1;         while (t>0)         {             x[t]+=1;             while (X[t]<=n &&!place (t))                 x[t]++;             if (x[t]<=n)               if (t = = N) {for (int k=1;k<=n;k++) printf ("%d  ", X[k]);p rintf ("\ n"); sum++;}            else                x[++t] = 0;             else              t--;         }         return sum;   }     int main ()   {       int t;  while (scanf ("%d", &n)) {t = Queen ();   printf ("%d\n", t); sum=0;}    return 0;   }  


V. Test results:


Vi. Summary

The annotations for iterative backtracking are similar to recursive backtracking, so they are no longer annotated. Here we can see that recursive backtracking is very simple, the structure is very clear, but it has a potential problem, that is, when the variable n increases, the complexity of the recursive method will also be a geometric growth, there may be duplication, so we solve the problem, if the iterative method can be solved, it is best not to use the recursive method, Unless you're already familiar with the recursion.
Through this n Queen's question, I think I have already made it very clear that the backtracking method is a tree, many methods can be solved by backtracking method, high efficiency, but if the base is too large, the backtracking method is not so applicable, this is the weakness of the backtracking method. For example, the N-Queen problem, as when n>60, backtracking can not completely solve the problem, then you may consider the probability algorithm to solve, it can solve a large base, but the result is not very accurate. Therefore, we face a problem, the specific use of what algorithm or the actual situation to consider, the purpose is more convenient and more accurate to solve the problem.

Huawei Machine test-N Queen problem (advanced topic 160 points: Two backtracking methods to solve vomiting of blood)

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.