machine trial-N queen problem (Advanced question 160 points: Two backtracking methods to solve vomiting blood sorting), 160 points

Source: Internet
Author: User



I. Problem description:
Place n queens that are not under attack on the chessboard of n × n grids. According to the rules of chess, the queen can attack pawns in the same row, column, or diagonal line. The problem after n is equivalent to placing n queens on the n × n board. Any two queens may wish to be on the same row, column, or diagonal line.
Input:
Given the size of the Board n (n ≤ 13)
Output:
How many placement methods are output.


Ii. solutions:
To solve the problem of Queen N, we need to solve how to place the Queen n. Each queen and all the queens in front cannot be in the same row, column, or diagonal line, here we can give priority to rows, that is to say, the Queen's row number increases in order and only considers which column of Queen I is placed in row I, therefore, when placing the queen I, you can judge from column 1st. If you can place the queen at the second position, you can jump to the next row and place the next queen. If not, jump to the next column... until the last column, if the last column cannot be placed, it indicates that the placement method is incorrect at this time, and the last queen is returned to the next column. This is the essence of the Backtracking Method. When the nth queen is successfully placed, a feasible solution is obtained, and then the last queen is placed again to find the next feasible solution... then, we can find all feasible solutions to the n queen problem.


Iii. Complexity Analysis:
The complexity of Queen N's question can be said to be different, and I have changed it several times. At first I thought the board was n rows and n columns, so it should be n ^ 2, later, it was found that the comparison of whether each column can be placed has made another loop, so it should be n ^ 3, but after a long time, it is found that when determining whether the data can be placed, it does not loop to n every time. It changes according to the value of Queen I, so the complexity should be around 1/3 n ^ 3, that is, less than n ^ 3.


Iv. Test code:
There are two implementation methods, one is Recursive Backtracking, and the other is iterative backtracking. The idea is the same, but the form is different.


Recursive Backtracking


# Include <stdio. h> # include <math. h> # define N 15 int n; // Number of Queens int sum = 0; // Number of feasible solutions int x [N]; // Number of columns placed by Queens/** judgment function, determine whether the Queen k can be placed in a certain position * If the queen and the former queen appear in the same column or the same diagonal line, the placement fails, and 0 is returned, otherwise, 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 ;} /** solves the feasible solution function. When the second queen can be placed in a certain position in the t row, the next queen will be placed until * all queens are placed, if a queen cannot be placed, move it to the next column. If this column cannot be placed * or all queens are placed, the last queen will be placed again and the number of all feasible solutions will be returned. */Int queen (int t) {if (t> n) // when the number of placed queens exceeds n, the number of feasible solutions plus 1 sum ++; else for (int I = 1; I <= n; I ++) {x [t] = I; // indicate that the queen t is placed in the column I if (place (t) // if it can be placed in a certain position, move another queen (t + 1 );} return sum;} int main () {int t; while (~ Scanf ("% d", & n) {t = queen (1); if (n = 0) // if n = 0, the number of feasible solutions is 0, in this case, do not ignore t = 0; printf ("% d \ n", t); sum = 0;} return 0 ;}



Iterative backtracking


#include <stdio.h> #include <math.h>  #define N 15     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]);printf("\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 annotation of iterative Backtracking is similar to Recursive Backtracking, so it is no longer mentioned. Here we can see that Recursive Backtracking is very simple and the structure is clear, but it has a potential problem, that is, when Variable n increases, the complexity of the recursive method will also increase in the geometric level, and there may be repeated situations. Therefore, if we can solve the problem through iterative methods, we 'd better not use recursive methods, unless you are familiar with this recursion.
Through this question of Queen N, I think we have already clearly explained the backtracking method. The solution obtained by the Backtracking Method is a tree. Many methods can be solved through backtracking, efficiency is very high, but if the base is too large, the backtracking method is not so suitable. This is also the weakness of the Backtracking Method. For example, the N queen's problem seems that when n> 60, the backtracking method cannot completely solve the problem. In this case, we can use the probability algorithm to solve the problem, it can solve a large base, but the results are not very accurate. Therefore, when faced with a problem, we need to consider the specific algorithm used or the actual situation in order to solve the problem more conveniently and accurately.


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.