Java implementation Eight Queen problem sample sharing _java

Source: Internet
Author: User

Question Description: Put eight queens on the chessboard, no two queens can attack each other (that is, no two queens on the same row, the same column or the same diagonal) as shown in the picture

In this article, there is a slightly different way to solve the two problems, but they all use one-dimensional arrays.  In 6.20, ask for an effective layout, I built a eight elements of an array, by randomly disrupting the value of the array, through the comparison between the value and subscript, until a valid layout, 6.22, required to find all the effective layout, where I used the number of octal, traversing the All numbers from 001234567-076543210 are converted to octal strings, and each digit is compared to its subscript to produce a layout that satisfies the condition. The implementation principles and methods are described in detail below.

Part 1 How to determine whether a valid layout

We treat the chessboard as a 8*8 matrix with a range of 0-7. Looking at the graph on the left, you can see that its layout can be represented by a set of pairs (from top to bottom), that is (0, 0), (1, 6), (2, 3), (3, 5), (4, 7), (5, 1), (6, 4), (7, 2). Represented by an array, that is, int []list = {0, 6, 3, 5, 7, 1, 4, 2};

Obviously, this is a valid layout. Here's a question to consider: In a valid layout, what does the subscript have to do with its corresponding value in the array, that is, I and list[i]?

Here we set list[i] = k;   LIST[J] = q; (i > J), they meet two conditions (it's easier to get a picture on paper):

1, k!= q;

2, I-j = = K-q or i-j = = Q-k (by the)

To ensure that K!= Q, here declares and initializes the array list, making list[i] = i. Then randomly shuffle the array, and then check to see if the condition 2

Copy Code code as follows:

To create and initialize an array
int [] list = new int [arrsize];
for (int i = 0; i < arrsize; i++)
List[i] = i;
Randomly scrambling arrays
public static void Randomizearray (int [] list) {
int arrsize = List.length;
int ranindex;
for (int i = 0; i < arrsize; i++) {
Ranindex = (int) (Math.random () * arrsize);
if (Ranindex!= i) {
int temp = List[i];
List[i] = List[ranindex];
List[ranindex] = temp;
}
}
}

The code body for 6.20 is as follows

Copy Code code as follows:

6.20 Games: Eight Queens
public void Solveeightqueens () {
int arrsize = 8;
int [] list = new int [arrsize];
for (int i = 0; i < arrsize; i++)
List[i] = i;
int count = 0;
Boolean notvalid = true;
while (Notvalid) {
Count + +;
Notvalid = false;
Randomizearray (list);

for (int i = 0; i < arrsize; i++) {
for (int j = i + 1; j < Arrsize; J + +) {
if (j-i = = Math.Abs (list[j]-list[i)) {//check to see if the condition is met
Notvalid = true;
Break
}
}
if (notvalid) break;
}//end of outer for loop
}//End of while

Print the result
int i;
System.out.println ("O (∩_∩) o haha ~, I have tried" + count + "times, and eventually succeed.");
for (i = 0; i < arrSize-1; i++) {
System.out.print ("+ i +", "+ List[i] +");
}
System.out.println ("+ i +", "+ List[i] +");
}

Part 2 to find out all the effective layout
Since 6.22 requires all valid eight-queen layouts, the randomly scrambled array method is no longer applicable and has to find a way to traverse all possible methods. One of the most straightforward methods is to use the eight-layer for loop, but the code is too large and the head is prone to faint, so this method is not used.

By looking closely at the values of the arrays in Part 1, you can see that they are all between 0-7, so traversing with the octal int can be guaranteed to include every permutation. Because the eight digits are different, the possible permutations are 8! = 40320 species, and the total number of octal is 8^8 = 16,777,216, so the possible proportions accounted for 40320/16777216 = 1/416, and the resulting 40,320 permutations have to be checked to filter out the final effective layout. The method is still a bit inefficient, but for the moment it hasn't come up with more efficient.

Copy Code code as follows:

6.22 Games: A variety of eight Queens Problem solution (increment with int value, then convert it to octal string, then check)
public static void Solveeightqueensmethod () {
int start = 001234567; Octal
int end = 076543210; Octal
int count = 0; Calculate the number of valid layouts
for (int i = start; i < end; i++) {
Boolean isValid = IsValid (i);
if (isValid) {

if (++count% 7 = 0)
System.out.println (integer.tooctalstring (i) + ":" + isValid);
Else System.out.print (integer.tooctalstring (i) + ":" + IsValid + "");
}
}
System.out.println ("Count =" + count); Number of valid layouts to output
}
Check if number is a valid layout
public static Boolean isValid (int number) {
String numoct = integer.tooctalstring (number);
int arrsize = Numoct.length ();
if (arrsize==7) {//If number first is 0, the generated string is only seven characters
Numoct = ' 0 ' + numoct;
Arrsize + +;
}
for (int i = 1; i < arrsize i + +) {
for (int j = i-1 J >= 0; j--) {
if (Numoct.charat (i) = = Numoct.charat (j)) return false; Same column
if (i-j = = Math.Abs (Numoct.charat (i)-Numoct.charat (j)) return false; Same diagonal line
}
}
return true;
}

Part 3 Extension: Problems with the build mix

Last year in a written examination, there is such a problem. Given a sequence, output all the combinations. Like what

Output of "123": 1, 2, 3, 12, 13, 21, 23, 31, 32, 123, 132, 213, 231, 312, 321

The output of "ABCD": A, B, C, D, AB, AC, ad, BA, BC, BD, CA, CB, CD, DA, DB, DC, ABC, ACB, Abd, ADB, ACD, ADC, ..., ABCD, ...

In 6.22, find all the eight-queen layout, using the method is to increase the number of int, and then check again. The above problem can be solved in a similar way. But the efficiency is a little low, if there is more efficient way, ask the expert to guide

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.