八皇后问题java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sun11462/article/details/47805213
八皇后问题java实现

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];//注意必须要拷贝到另外一个数组
        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("第"+(count+1)+"种解法");
	        count++;
		}else{
		for(int j=0;j<n;j++){
			if(notDanger(chess,row,j)){    //注意这里判断的是chess数组而不是chess2数组
				for(int i=0;i<n;i++){
					if(chess2[row][i]!=0){
						System.out.println("row为"+row);
						System.out.println("j为"+j);
						System.out.println("第"+(count+1)+"种解法");
				        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;    //这里必须把该行的值都清零,因为在一行中可能存在有多个位置都满足条件,for循环会将每个安全的位置都置为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++){     //注意这里判断的是列安全,不需要判断行安不安全。
			
			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;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/sun11462/article/details/47805213