package problem.回溯; public class EightQueue { public static int max = 8,sum = 0; public static int[] queen = new int[max]; //存储列元素值 //皇后元素形式:(i,queue[i]) public void displayQueen(){ for(int i=0;i<queen.length;i++) { System.out.print("("+i+","+queen[i]+")"); } System.out.println(); sum++; } public boolean check(int n){ for(int i=0;i<n;i++){ //判断元素不在同一列和对角线上 if(queen[i]==queen[n] || Math.abs(queen[i]-queen[n])==(n-i)){ return false; } } return true; } public void put(int n){ for(int i=0;i<max;i++){ queen[n] = i; //把该列上的每个元素尝试一下 if(check(n)){ if(n==max-1) displayQueen(); else put(n+1); } } } public static void main(String[] args) { EightQueue eq = new EightQueue(); eq.put(0); System.out.println("sum="+sum); } }