C # using recursive algorithm to solve the eight queen problem _c# tutorial

Source: Internet
Author: User
Tags first row

1. Intro

There is an old saying in China called "do not hit the south wall do not look back", vivid description of a person's stubbornness, a bit derogatory, but in software programming, this kind of thinking is really a problem solving the simplest algorithm, it is similar to reckless thinking, step by step forward, each step is closer to the goal of some of the results, We didn't consider going back until we met the obstacle. And then go ahead and try to move forward. Through this kind of wave forward method, finally reach the destination. Of course, the whole process requires a lot of round-trip, such a way forward, the efficiency is relatively low.

2. Scope of application

It is suitable for those problems that do not exist concise mathematical models to clarify the nature of the problem, or the existence of mathematical models, but difficult to achieve.

3. Application Scenarios

On the 8*8 chess board, a queen is required to be placed on each line, and in the vertical direction there is no conflict in the oblique direction. The chess board is shown in the following illustration:

4. Analysis

Basic ideas such as the above analysis of the same, we use the step-by-step approach, first from a direction forward, can enter into the, not into the retreat, try another path. Let us first analyze the rules of chess, which can limit our progress, that is, obstacles in our way. A queen Q (x,y) can be eaten by Queen Q (Row,col), which satisfies the following conditions

1) X=row (no more than two queens in portrait)

2) Y=col (transverse)

3 col + row = y+x; (Oblique direction)

4) Col-row = Y-x (oblique opposite direction)

When one of these problems is encountered, it means that we have encountered obstacles and cannot move forward. We need to come back and try other paths.

We think of the chessboard as a 8*8 array, so we can use a reckless way of thinking to solve the problem, so that we are 8*8=64 in the grid to take out 8 combinations, C (64,80) = 4426165368, obviously this number is very large, on the basis of reckless we can increase backtracking, From the No. 0 column, we proceed column by row, from line No. 0 to 7th to find a place that is not under the attack of any existing queens, and the fifth column, we will find that the Queen's safe position is not found, the previous four columns are as follows:

In the fifth column, put any line will be shown above the image of the existing Queen's attack, when we think we hit the south wall, is the time to turn back, we back a column, the original placed in the fourth column of the Queen (3,4) take away from this position (3,4), start, Let's look for the next safe position in column fourth (7,4), then go to column fifth, and find that column fifth still has no secure location, back to fourth, and the fourth column is a dead end, and we'll go backwards to the third column, so we can step forward Eventually, a safe location (success) was found on column 8th, or the first column was a dead end, but column 8th still did not find a safe location.

To sum up, the steps to solve the 8 queens problem with backtracking methods are:

1 start with the first column, find a safe location for the queen, and then jump to the next column

2 If there is a dead end in column N, if the column is listed in the first row, the chess game fails, or it goes back to the previous column, backtracking

3 If a safe position is found on the 8th column, the chess game is successful.

All 8 queens have found a safe position. Represents the success of the chess game, with a length of 8 integer array queenlist represents the successful placement of the 8 Queens, the array index represents the col vector of the chessboard, and the value of the array is the row of the chessboard

Quantity, so (Row,col) The Queen can be expressed as (Queenlist[col],col), as in the above figure several queens can be expressed as:

Queenlist[0] = 0;   QUEENLIST[1] = 3;  QUEENLIST[2] = 1;   QUEENLIST[3] = 4; Queenlist = 2;

Let's take a look at how to design a program:

First, determine whether (Row,col) is a safe location algorithm:

BOOL Issafe (int col,int row,int[] queenlist)
{
 //Check only the preceding column for
 (int tempcol = 0; Tempcol < col; tempcol++) 
   {
  int temprow = Queenlist[tempcol];
  if (Temprow = = row)
  {
   //return false on the same line
   ;
  }
  if (Tempcol = = col)
  {
   //the same column return
   false;
  }
  if (Temprow-tempcol = = Row-col | | Temprow + Tempcol = = row + col)
  {return
   false;
  }
 }
 return true;
}

Set a function to find the Queen placement method after the Col column:

<summary>
///Search for a secure row value in column col
///</summary>
///<param name= "Queenlist" ></ param>
///<param name= "col" ></param>
///<returns></returns> public
bool Placequeue (int[] queenlist, int col)
{
 int row = 0;
 BOOL Foundsafepos = false;
 if (col = 8)//End flag
 {
  //when finished completing Foundsafepos = True of the 8th column
  ;
 }
 else
 {
  while (Row < 8 &&!foundsafepos)
  {
   if (Issafe (col, Row, queenlist))
   {
    Find safe location
    Queenlist[col] = row;
    Find the safe location for the next column
    Foundsafepos = Placequeue (queenlist, col + 1);
    if (!foundsafepos)
    {
     row++
    }
   }}
   else
   {
    row++;
   }
 }} return foundsafepos;
}

Call Method:

 static void Main (string[) args) {Eightqueen eq = new Eightqueen ();
 int[] queenlist = new Int[8];
  for (int j = 0; J < 8; J +) {Console.WriteLine ("-----------------" +j+ "---------------------");
  Queenlist[0] = j; BOOL res = eq.

  Placequeue (queenlist, 1);  
   if (res) {Console.Write ("");  
   for (int i = 0; i < 8; i++) {Console.Write ("" + i.tostring () + "");
   } Console.WriteLine ("");      
    for (int i = 0; i < 8; i++) {Console.Write ("" +i.tostring () + "");
     for (int a = 0; a < 8; a++) {if (i = = Queenlist[a]) {console.write ("q");
     else {console.write ("*");
      
   } Console.WriteLine ("");
  } Console.WriteLine ("---------------------------------------"); else {Console.WriteLine ("Unable to complete the chess game, the chess failed!")
  ");
} console.read (); }

Recursive algorithm Placequeue, complete this function: It looks for the col after the Queen's safe placement, if the function returned false, indicating that the current entered a dead end, need to backtrack, until the 0-7 column to find

Stop when you are in a safe place or find a safe location for these columns.

A recursive algorithm to solve the 8 queen problem of the sample program:

Http://xiazai.jb51.net/201606/yuanma/EightQueens (jb51.net). rar

Related Article

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.