利用递归+回溯实现八皇后问题解法
public class EightQueens {
private static int count;
private static int judgeCount;
public static void main(String[] args) {
//set the max count of queens
int maxNum = ConstUtil.MAX_QUEENS;
//this array contains the point of eight queens
//the index of this array equals the serial number of these queens
int[] points = new int[maxNum];
setQueen(0, points);
System.out.println("一共解法有" + count + "种");
System.out.println("一共回溯了" + judgeCount + "次");
}
/**
* set the num queen
*
* @param num
* @param points
*/
private static void setQueen(int num, int[] points) {
//end reason
if (num == points.length) {
count++;
printf(points);
return;
}
//suppose every row from 0 to maxNum
for (int i = 0; i < points.length; i++) {
points[num] = i;
//judge this queen can set this point
if (judgePoint(num, points)) {
//success to set next queen
setQueen(num + 1, points);
}
}
}
/**
* judge
*
* @param num
* @param points
* @return
*/
private static boolean judgePoint(int num, int[] points) {
judgeCount++;
for (int i = 0; i < num; i++) {
if (points[num] == points[i] || Math.abs(num - i) == Math.abs(points[num] - points[i])) {
return false;
}
}
return true;
}
private static void printf(int[] points) {
for (int i = 0; i < points.length; i++) {
System.out.print("(" + i + "," + points[i] + ")\t");
}
System.out.println();
}
}