八皇后问题(回溯算法)

代码

public class Queue8 {
	
	//有几个皇后
	int max = 8;
	//皇后存放位置的结果
	int[] array = new int[max];
	static int count = 0;
	static int judgeCount = 0;
	public static void main(String[] args) {
		Queue8 queue8 = new Queue8();
		queue8.check(0);
		System.out.printf("总共有%d种解法
",count);
		System.out.printf("一共判断冲突的次数是%d次
",judgeCount);
	}
	
	//放置第n个皇后
	//特别注意:check是每一次递归,进入check中,都有for (int i = 0; i < max; i++),因此会有回溯
	private void check(int n){
		//够了8个皇后
		if(n == max){
			print();
			return;
		}
		for (int i = 0; i < max; i++) {
			//先把当前这个皇后n,放在该行的第一列
			array[n] = i;
			//判断当放置第n个皇后到i列时,是否冲突
			if(judge(n)){//不冲突
				//接着放n+1个皇后,即开始递归
				check(n + 1);
			}
		}
	}
	
	//查看当我们放置第n个皇后,就去检测该皇后是否和前面已经摆放的皇后冲突
	//n表示放置第n个皇后 从0开始
	private boolean judge(int n){
		judgeCount ++;
		for (int i = 0; i < n; i++) {
			//array[i] == array[n] 判断第n个皇后是否和前面的某个皇后在同一列
			//Math.abs(n - i) == Math.abs(array[n] - array[i]) 
			//判断第n个皇后是否和前边的某个皇后在同一斜线
			if(array[i] == array[n] || Math.abs(n - i) == Math.abs(array[n] - array[i])){
				return false;
			}
		}
		return true;
	}
	
	//将皇后摆放的位置输出
	private void print(){
		count ++;
		for (int i = 0; i < array.length; i++) {
			System.out.print(array[i] + " ");
		}
		System.out.println();
	}
}

结果

0 4 7 5 2 6 1 3 
0 5 7 2 6 3 1 4 
0 6 3 5 7 1 4 2 
0 6 4 7 1 3 5 2 
1 3 5 7 2 0 6 4 
1 4 6 0 2 7 5 3 
1 4 6 3 0 7 5 2 
1 5 0 6 3 7 2 4 
1 5 7 2 0 3 6 4 
1 6 2 5 7 4 0 3 
1 6 4 7 0 3 5 2 
1 7 5 0 2 4 6 3 
2 0 6 4 7 1 3 5 
2 4 1 7 0 6 3 5 
2 4 1 7 5 3 6 0 
2 4 6 0 3 1 7 5 
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