package backtracking;
/**
*
运用递归做的"八皇后"经典问题,掌握回溯思想
* @author LeLe
*
*/
public class EightQueen {
//
竖线
boolean[] line = new boolean[4];
//
左对角线
boolean[] leftDiagonal = new boolean[7];
//
右对角线
boolean[] rightDiagonal = new boolean[7];
//y
坐标存储
int[] lineS = new int[4];
public EightQueen(){
line[0] = line[1] = line[2] = line[3] = true;
for (int i = 0; i < leftDiagonal.length&&i < rightDiagonal.length; i++) {
leftDiagonal[i] = true;
rightDiagonal[i] = true;
}
}
public void putQueen(int row){
for (int i = 0; i < line.length; i++) {
if(line[i]==true&&leftDiagonal[row+i]==true&&rightDiagonal[row-i+3]==true){
//
操作成功
line[i] = false;
leftDiagonal[row+i] = false;
rightDiagonal[row-i+3] = false;
lineS[row] = i;
if(row<line.length-1){
this.putQueen(row+1);
}else if(row == line.length-1){
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
for (int j = 0; j < line.length; j++) {
System.out.println("
皇后坐标为"+j+" "+lineS[j]);
}
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
}
line[i] = true;
leftDiagonal[row+i] = true;
rightDiagonal[row-i+3] = true;
}
}
}
public static void main(String[] args){
EightQueen queen = new EightQueen();
long a = System.currentTimeMillis();
queen.putQueen(0);
long b = System.currentTimeMillis();
System.out.println("
执行时间为 "+(b-a)+"毫秒");
}
}