Eight Queens question Java implementation

Source: Internet
Author: User

Eight Queens question Java implementation
public class Eightqueen {public static int count=0, public static void main (string[] args) {int chess[][]=new int [8      ][8]; Search (chess,0,8);} static void search (int chess[][],int row, int n) {int chess2[][]=new int [8][8];//Note must be copied to another array for (int i=0;i<n  ; i++) {for (int j=0;j<n;j++) {chess2[i][j]=chess[i][j];        }}if (row==8) {System.out.println ("n" + (count+1) + "solution"); count++;} else{for (int j=0;j<n;j++) {if (Notdanger (chess,row,j)) {//Note here is inferred Chess array instead of CHESS2 array for (int i=0;i<n;i++) {if ( chess2[row][i]!=0) {System.out.println ("row for" +row); System.out.println ("J for" +j);        System.out.println ("count+1" + "Seed solution");    for (int t1=0;t1<n;t1++) {for (int t2=0;t2<n;t2++) {System.out.print (chess2[t1][t2]+ "");      } System.out.println ();    }}chess2[row][i]=0; The value of the row must be zeroed out here. Because there may be multiple locations in a row that meet the criteria, the for loop will place each safe position at 1.} Chess2[row][j]=1;search (Chess2,row+1,n);}}} private static Boolean Notdanger (int[][] chess2, int row, int j) {Boolean flag1=false,flag2=false,flag3=false,flag4=false,flag5=false;for (int i=0;i < 8;i++) {//Note that the column security is inferred, there is no need to infer that row safety is unsafe. 

if (chess2[i][j]!=0) {flag1=true;break;}} for (int i=row, k=j;i>=0&&k>=0;i--, k--) {if (chess2[i][k]!=0) {flag2=true;break;}} for (int i=row, k=j;i<8&&k<8;i++,k++) {if (chess2[i][k]!=0) {flag3=true;break;}} for (int i=row, k=j;i>=0&&k<8;i--, k++) {if (chess2[i][k]!=0) {flag4=true;break;}} for (int i=row, k=j;i<8&&k>=0;i++,k--) {if (chess2[i][k]!=0) {flag5=true;break;}} if (flag1| | flag2| | flag3| | flag4| | FLAG5) {return false;} Else{return true;}}}


Eight Queens question Java implementation

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.