Eight Queens-N Queens Problem-Illustrated Java

Insert picture description hereIdea: I believe everyone already knows the meaning of a classic question like the Eight Queens, what should we do? Let's take
an example: Insert picture description herethe premise that the green dot can exist is that 它的左下方的那条斜线上、右上方那条斜线上以及它所在的这一列和这一行上there is no other "queen", so the four conditions we need when we search come out.

According to the meaning of the title, we will finally output an array. The example given by the title 2,4,6,1,3,5means that the "Queen" in the first row should be placed in the second column, and the queen in the second row should be placed in the fourth column, and so on. , So we can use a one-dimensional array to represent all the states, that is arr[i]=j 第i行的皇后应该放在第j列, in this way, we don’t need to judge whether there are other "queen" on the same line, because the search is from the next level up, This way it will definitely not be on the same line.

Now there are three conditions 1.左下方斜线 2.右上方斜线 3.同一列上. Let’s take a look at the relational Insert picture description here
word ugly from the picture. We hope that we don’t mind.
We can use the array to determine whether there is a "Queen" in the left and right diagonal of the point
left[x+y]=true 表示x,y这点的左斜已经有皇后了,left[x+y]=boolean,则表示没有.

The point in the example is special, xy will not be less than zero, but in actual operation there will be points less than zero, so we have to add n to each value of xy to ensure that the coordinates are not negative right[x-y+n]. As for why we don’t use absolute values You can try it.

Determine whether the "Queen" already exists on the column, and open an array as above.

code show as below:

import java.util.Scanner;
public class Main {
    
    
		
		    static boolean left[]=new boolean[40];   //:左上到右下      在同一条斜线上的横坐标减纵坐标绝对值相等
			static boolean right[]=new boolean [40];  //:右上到左下	   在同一条斜线上的横坐标加纵坐标值相等
			static boolean lie[]=new boolean[40];
			static int count=0;  //计算个数,超过三个就不输出了
			static int a[]=new int[40];
			
		
			public static void main(String[] args) {
    
    
				Scanner input=new Scanner(System.in);
				int n=input.nextInt();
				DFS(1,n);
                System.out.println(count);
			
			}
		public static void DFS(int x,int n) {
    
    
			if(x>n) {
    
    
               if(count<=2){
    
    
				for(int i=1;i<=n;i++)
					System.out.print(a[i]+" ");
				System.out.println();
				
}
                count++;
				return ;
			}
			for(int i=1;i<=n;i++) {
    
    
				if(!lie[i]&&!left[x-i+n]&&!right[x+i]) {
    
    
					lie[i]=true;
					left[x-i+n]=true;
					right[x+i]=true;
					a[x]=i;
					DFS(x+1,n);
					//回溯
					lie[i]=false;
					left[x-i+n]=false;
					right[x+i]=false;
				}
				
			}
			
		}

}

Guess you like

Origin blog.csdn.net/qq_44844588/article/details/107939488