Data structure application case--stack structure for 8 Queens Problem backtracking solution

Source: Internet
Author: User

"description" This article is from the Zhou Shiping teacher in chief editor of the "C language programming" textbook. I wrote the 7th and 8 chapters as a part of the editing staff. The "8.6.1 backtracking method" in "The 8th chapter problem solving and algorithm" takes the solution of 8 queens problem as an example, and introduces the process of solving problems in backtracking method. The "stack" is used in this solution and is cited here as an example of a stack application. It should be stated that the textbook is intended for beginners in programming and does not offer any description of "stack" in the full text. Doing so hides the terminology and reduces the beginner's cognitive difficulty. For the data structure learners, because of the expansion of knowledge, but do not need to avoid such terminology. Therefore, when reading this article, as the application of the experience stack, it is necessary to extract the application stack storage and processing parts.

Full-text
Backtracking is a general-purpose search algorithm that can be used to solve almost any computable problem. The execution of the algorithm is like searching a maze for a route to the exit, always in a certain direction to explore, if you can walk, then continue to move forward, if you do not go through, you have to mark, in another direction to continue to test, until the solution of the problem, or all may have been tempted so far.
Below, use the classic 8 queen question as an example to explain how to use backtracking thinking to solve the problem.

8 The Queen's question is: Put 8 queens on the 8x8 board so that they cannot attack each other, i.e. any two queens cannot be on the same line, in the same column, or on the same slash. The eight Queen question can be extended to the question of n queens, that is, placing n Queens on the NXN board, so that any two queens cannot be on the same line, in the same column, or on the same slash.

The first thing you need to do is describe the board. Intuitively, the chessboard can be represented by a two-dimensional array, with the Queen's chess grid corresponding to the array element value is 1, no queen of the corresponding array element value is 0. But this storage structure is not the simplest and most effective choice.
Figure 8.21 in the left part of the board of the row, column numbered, provide the placement method, is a solution to the problem. On the right, the number of columns on each line is recorded, with these 8 numbers (4, 6, 8, 2, 7, 1, 3, 5), which also constitute a description of the problem solution.

Figure 8.21 8 A solution to the Queen's problem

As you can see, you can define a one-dimensional array int x[n], and the value of X[i] indicates the number of columns of the Queen on line I, the solution of the N queen problem can be used (x[1], x[2], ... X[n]) in the form of a description.
Solve the problem of data representation, design the method of data processing. This paper uses the backtracking strategy to design the computer's solution to the N queen problem. Take 4 Queens as an example, 8.22, in Figure 8.22 (a), place a queen on the 1th column of row 1th, figure 8.22 (b) to determine the possible placement of line 2nd, after attempting to abort the 1th column, the 2nd column due to mutual attack, determine the position in the 3rd column can continue, in Figure 8.22 (c) Continued on the 3rd line of investigation, found that all 4 columns have been tried, there is no way to put the Queen to a suitable location, no attempt to do any of the 4th line is meaningless, then the result is a retrospective, in Figure 8.22 (d) in the 2nd row of the Queen to the 4th column, and then the 3rd line temporarily can be placed in the 2nd In Figure 8.22 (e), trying to determine the queen of line 4th, but found that no solution again backtracking, only to 8.22 (f) to the 1th row of the Queen in column 2nd, and then Figure 8.22 (g), (f) to find a solution to the 4 queen question, that is, figure 8.22 (g) (2, 4, 1, 3)

Figure 8.22 The process of finding a solution to the 4 queen problem with backtracking

In Figure 8.23, a description of the complete process for finding out all the solutions of the 4 Queens problem is given. Figure (1 * * *) corresponds to Figure 8.22 (a) in the 1th row of the Queen arranged in the 1th column, the other row pending status, the next (1 3 * *) corresponds to Figure 8.22 (b) in the 2nd row of the Queen arranged in the 3rd column state. It can be determined that in this state, the continuation of the attempt is not able to complete the solution, so the backtracking (b below it for backtracking), so the next attempt will be the status (1 4 *), .... This process will continue to be able to find all the solutions of the 4 Queens Problem (2 4 1 3) and (3 1 4 2), and 8.23 the nodes in the grid background.

Figure 8.23 Finding the complete process of all the solutions of the 4 Queens problem

After figuring out how to use backtracking to solve the process, we will focus on how to base (X[1], x[2 ... X[n]) Form the structure of the solution, write the computer to complete the solution process code. 4 Queen's problem can be drawn on paper, 8 queen of the problem of the possible solution has 8!=40320 species, the Final solution has 92 kinds, must rely on computer solution.
What kind of Jia Cai is feasible? Need to describe a condition in which any two queens can "attack each other":
(1) There are two queens on the same line: the structure of the solution (X[1], x[2], ... X[n]) has guaranteed that no two queens will appear on the same line.
(2) There are two Queens in the same column: expressed as x[i]=x[k], if in Figure 8.23 is shown as (1 1 * *), (4 2 3 2) such as nodes, then there are two queens in the same column.
(3) There are two queens in the same slash: If the two queens are placed in line I, X[i], section K, X[k], if they are on the board with a slope of 1 on the diagonal, meet the conditions i-x[i]=k-x[k], for example (1 4 3 *), (4 1 2 *) If they are on a diagonal line with a slope of 1 on the board, satisfy the condition i+x[i]=k+x[k]. Transform these two equations into i-k=x[i]-x[k] and i-k=x[k]-x[i], for example (3 4 1 *). In both cases, two queens are represented as |i-k|=|x[i]-x[k]| on the same slash.
In the following program implementation, the place (x, K) function is used to determine if the Queen is placed in column K X[k], and whether it will attack each other with the Queen placed above. As long as the queen of a row (line i) is in the same column as the Queen of the K-line (X[i]=x[k]) or is in the same slash (|i-k|=|x[i]-x[k]|), it returns False (0) immediately, indicating that the solution cannot be formed.
Next, in the implementation of the problem solving nqueens (x, N) function, starting from the 1th line, row by column to examine the Queen's placement, when encountering a row all possible situations try not to go further to the next line of investigation, in a timely manner back to the previous line, and then examine.
In a program implementation, an array of saved solutions is defined as a dynamic array. Allocate more than one cell, because the first element of the array x[0] has been idle, and the useful unit is x[1] to x[n].
  
"Example 8.12" procedure for solving the 8 Queens problem

#include <stdio.h>#include <math.h>#include <malloc.h>voidNqueens (int*x,intn);/ * Solve the N Queen problem * /intPlaceint*x,intk);/ * Determine if the Queen can be placed in section K x[k] * *voidPrintsolution (int*x,intn);/ * Output Solution results * /intMain () {intNint*x;/ * The first address of the array to store solution results * /    scanf("%d", &n); X= (int*)malloc(sizeof(int) * (n+1));/ * Dynamically allocated array space, X[0] idle * /Nqueens (x, N);return 0;}/ * If a queen can be placed in section K x[k] column, return True (1), otherwise false (0) */intPlaceint*x,intK) {intI/ * On the front k-1 line, line-by-row study * /     for(i=1; i<k; i++) {/* If the first k-1 line has a row of Queens with the K line in the same column or the same slash, return 0*/        if((X[i]==x[k]) | | (fabs(X[i]-x[k]) = =fabs(i-k)))return 0; }/ * You can execute the next sentence, stating that the Queen is placed in column K X[k] and will not attack each other * *    return 1;}/ * Solve on the NXN board, Place n Queens so that they can't attack each other * /voidNqueens (int*x,intN) {intK K =1;/*k is the current line * /X[K] =0;/*x[k] is the forefront, into the loop, immediately executes the x[k]++, and selects the 1th column * /     while(k>0)/* When all possible solutions have been tried, K will become 0, ending the solve process */{x[k]++;/ * Move to the next column * /         while(X[k]<=n &&!place (x, K))/ * Search by column to find the columns that can be placed on the Queen x[k]*/x[k]++;if(x[k]<=n)/ * Find a place to put the Queen * *{if(k==n)/ * is a complete solution, output solution * /Printsolution (x, N);Else  / * Does not complete the last line selection, is part of the solution, to the next line * /{k++;/ * Proceed to the next line * /x[k]=0;/ * After the loop has started executing x[k]++, the next line will be examined from column 1th * /}        }Else  / * For the case of X[k]>n, this line has no need to retry, back to the previous line * /k--;/ * The previous line starts with the next 1 columns in the original x[k] column * /}}/ * Output Solution results * /voidPrintsolution (int*x,intN) {intI, J; for(i =1; I <= N; i++)/ * Output line I/*{ for(j=1; j<=n; J + +) {if(j = = X[i])/ * Section x[i] column output q, other column output * * *                printf("Q");Else                printf("*"); }printf("\ n"); }printf("\ n");}

"Study questions" from the problem solving strategy and procedures, find out where the stack is used, how to apply the stack to the backtracking process?

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Data structure application case--stack structure for 8 Queens Problem backtracking solution

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.