Eight Queens Java algorithm

Source: Internet
Author: User

The eight Queens question, an old and famous problem, is a typical case of backtracking algorithms. The issue is the international chess player Max Bessel in 1848: Put eight queens on the 8x8 chess, so that they can not attack each other, that is, any two queens can not be in the same row, the same column or the same slash, ask how many kinds of pendulum

public class Queen{
private int [] column; //右上至左下是否有皇后 private int [] rup; //左上至右下是否有皇后 private int [] lup; private int [] queen; private int num; public Queen(){ column= new int [ 8 + 1 ]; rup= new int [( 2 * 8 )+ 1 ]; lup= new int [( 2 * 8 )+ 1 ]; for ( int i= 1 ;i<= 8 ;i++) column[i]= 0 ; for ( int i= 1 ;i<=( 2 * 8 );i++) rup[i]=lup[i]= 0 ;   //初始定义全部无皇后 queen= new int [ 8 + 1 ]; } public void backtrack( int i){ if (i> 8 ){ showAnswer(); } else { for ( int j= 1 ;j<= 8 ;j++){ if ((column[j]== 0 )&&(rup[i+j]== 0 )&&(lup[i-j+ 8 ]== 0 )){ //若无皇后 queen[i]=j; //设定为占用 column[j]=rup[i+j]=lup[i-j+ 8 ]= 1 ; backtrack(i+ 1 );   //循环调用 column[j]=rup[i+j]=lup[i-j+ 8 ]= 0 ; } } } } protected void showAnswer(){ num++; System.out.println( "\n解答" +num); for ( int y= 1 ;y<= 8 ;y++){ for ( int x= 1 ;x<= 8 ;x++){ if (queen[y]==x){ System.out.print( "Q" ); } else { System.out.print( "." ); } } System.out.println(); } } public static void main(String[]args){ Queen queen= new Queen(); queen.backtrack( 1 ); } }

Eight Queens Java algorithm

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.