zoukankan      html  css  js  c++  java
  • 八皇后问题java实现

    八皇后问题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; } } }


  • 相关阅读:
    python—打开图像文件报错
    CTFshow萌新赛-萌新福利
    微信小程序bug
    微信小程序
    架构
    命令行
    MyBatis
    avalon
    并发测试工具
    less
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/7091104.html
Copyright © 2011-2022 走看看