Solving eight queens problem by backtracking

Source: Internet
Author: User
Tags abs
Problem Description:The eight Queens question is a chess-based question: how can you place eight queens on an 8x8 chess board so that no queen can directly eat the other queens? To achieve this, neither of the two queens can be in the same row, vertical line, or slash.

Problem History:The eight Queens issue was first introduced by chess player Max Bessel in 1848. Later, mathematicians studied them, including Gauss and Cantor, and promoted them to the more general problem of placing n queens. The first solution to the eight Queens question was given by Franz Nock in 1850. It is also one of the first to generalize the problem to a more general N-Queens placement problem. In 1874, S. Gandre proposed a method that was solved by determinant, and this method was later improved by J.W.L. Glaisher.



Conversion Rules:In fact, the problem of the eight queens can be generalized to the more general N Queen placement problem: Then the size of the board becomes NXN, and the number of Queens becomes N. The problem has a solution when and only if n = 1 or n≥4. Make an array a[n] save the solution, where a[i] means the number of columns in row I of the Empress I (note that the value of I is calculated from 0), the following is a simple rule-to-problem extraction process for the eight Queens problem.
(1) Because all queens cannot be placed in the same column, the array cannot have the same two values.
(2) All Queens cannot be on the diagonal, so how to detect whether the two queens are on the same diagonal. We will make the checkerboard into a two-dimensional array, as follows:

Suppose there are two queens placed in (I,J) and (k,l) positions, obviously, when and only if |i-k|=|j-l| , two queens are on the same diagonal line.

Algorithm Prototypes:As we figure out the two rules that we need to deal with before we solve the eight queens problem, and turn the rules into questions about our mathematical models, we begin to discuss how to design the eight queen's Problem of solving algorithms, the most common of which is backtracking and what is the backtracking method.
The Backtracking method (English: Backtracking) is one of the exhaustive search algorithms (English: Brute-force searches).

The backtracking method uses the thought of trial and error, and it tries to solve a problem by step. When it comes to solving a problem in steps, when it tries to discover that the existing step answer is not valid, it will cancel the previous or even previous steps, and try again to find the answer to the question again through the other possible steps. Backtracking is usually done with the simplest recursive method, and there are two possible scenarios after repeating the above steps:

* Find the right answer that might exist
* After attempting all possible step methods, declare the question without an answer

In the worst case, backtracking results in an exponential time calculation of the complexity.

Obviously, the thought of backtracking is: assuming that the current state of a behavior, constantly check whether the row all the position can put a queen, retrieving the status of two kinds:
(1) First check from the first, if unable to place, then check the second position of the row, and then check down, until the line to find a place where you can place a queen, and then save the current state, go to the next line to repeat the above method of retrieval.
(2) If all the positions of the line are checked, a queen cannot be placed, stating that the position of the Queen placed on the previous line does not allow all queens to find their proper position, so go back to the previous line and recheck the position behind the Queen's position.

whether to notice. If we use an array to hold the current state, the above retrieval process is a bit like a stack operation. If a workable position is found, the stack will be stacked if all the positions in the current row are not available. Well, the problem model is getting clearer, and we can define a process that is responsible for retrieving the process, and if it is possible to retrieve a position in the current row, the stack will be executed if all the positions in the current row are not working. 8 Queen problem, we assume that the stack size is 8, if the stack is full, indicating that a viable method is found, all the out-of-stack operations will be performed. Maybe a reunion asked: If I find a way to find the next feasible method, how to do to find the method does not repeat. Whether we need to set a state variable for each row. In fact, the method of handling this problem is very simple: in fact, when we are backtracking, each queen position is the state variable of the row, back to the next position, only a 1-bit backward, that is, i++.

OK, in fact, we can use an array to simulate the structure of the stack can be, the above explanation without arrays and use the stack because the structure of the stack is more image than the array. Based on the above idea, we have to define a process that checks to see if a position in the current row is feasible, and I use the usual algorithm description language SPARKS to facilitate reading. One of the biggest features of SPARKS is the idea of the algorithm rather than the code, which helps the reader to understand the author's algorithmic ideas more clearly and concisely.

(1) Process Place, retrieves whether the current row can be placed on a queen.
  procedure  place (k)
  //returns True if a queen can be placed in the K-line and X (k) columns, otherwise false. X is a full array, and K values have been set when entering this procedure. The ABS (r) process returns the absolute value of R//
     Global  x (1:k); Integer  i,k
    i←1
     while  i <k  do
        if
 x (i) =x (k)   or  abs (X (i)-X (k)) =abs (i-k)
          &NBSP;&NBSP  then return   (false)
              endif
             i←i+1
         repeat
         return
  (true)
end  Place

(2) using the above search process, by recursive way, to determine the position of each Queen ——— backtracking thought
Procedure Nqueens (N)
This procedure uses backtracking to find all possible locations where n queens are placed on a n*n chessboard, so that they cannot attack each other.
Integer k,n,x (1:n)
X (1) ←0;k←1//k is the current line, X (k) is the position of the current row
While k>0 do
X (k) ←x (k) +1//move to next position
While X (k) <=n and not places (k) do//Can I put this queen here?
X (k) ←x (k) +1
Repeat
If X (k) <=n//Find a location//
Then if K=n//is a complete solution. //
Then print (X)//Yes, print array//
else k←k+1; X (k) ←0//Turn to the next line//
endif
else k←k-1//Otherwise, retrace the previous line//
endif
Repeat
End Nqueens


The realization of the problem of the C language eight queens:
#include <stdio.h>
#include <stdlib.h>
#define MAX 8
int Queen[max], sum=0; /* Max is the checkerboard's maximum coordinates */

void Show ()/* Outputs all Queen's coordinates */
{
int i;
printf ("(");
for (i = 0; i < max; i++)
{
printf ("%d", queen[i]);
}
printf (") \ n");
sum++;
}

int place (int n)/* Check if the current column can be placed Queen */
{
int i;
for (i = 0; i < n; i++)//check to see if Queens can be placed on the horizontal and diagonal * *
{
if (queen[i] = = Queen[n] | | ABS (QUEEN[I]-queen[n]) = = (N-i))
{
return 1;
}
}
return 0;
}

void Nqueens (int n)/* Backtrack attempt Queen position, n is horizontal */
{
int i;
for (i = 0; i < max; i++)
{
Queen[n] = i; /* Place the Queen in the current loop */
if (! Place (n))
{
if (n = = max-1)
{
Show (); /* If all is set, the coordinates of all queens are output */
}
Else
{
Nqueens (n + 1); /* Otherwise continue to place the next queen * *
}
}
}
}

int main ()
{
Nqueens (0); /* Start with the horizontal axis of 0 to try */
printf ("%d", sum);
System ("pause");
return 0;
}
Comment on this one

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.