递归-八皇后案列


package recursion;

/**
 * 
 * 八皇后案例
 *
 */

public class EightQueens {

    private static int MAX = 8;
    
    private static int arr[] = new int[MAX];
    
    private static int COUNT = 0;
    
    public static void main(String[] args) {
    
        calculation(0);
        
        System.out.println("一共有" + COUNT + "次");
    }
    
    
    public static void calculation(int n) {
        if (n == MAX) {
            print();
            COUNT += 1;
            return;
        }
        
        for (int i = 0; i < arr.length; i ++) {
            arr[n] = i;
            if (isContain(n)) {
                calculation(n + 1); 
            }
            
        }
    }
    
    public static boolean isContain(int n){
        /// 先遍历第一列0皇后所有的解  n才会加1遍历所以1的解所以i < n
        for (int i = 0; i < n; i ++) {
            /// 计算是否再同一条线上 || 计算是否在同一条斜线上
            if (arr[i] == arr[n] || Math.abs(n - i) == Math.abs(arr[n] - arr[i])) {
                return false;
            }
        }
        
        return true;
    }
    
    public static void print() {
        for (int i = 0; i < arr.length; i ++) {
            System.out.print(arr[i] + "\t");
        }
        System.out.println();
    }
}
 

运行结果


1585987646(1).png

你可能感兴趣的:(递归-八皇后案列)