回溯查找是一种暴力查找方法,查找的过程中用约束的条件进行判断,进行回溯。八皇后就是不能处于同列对角,进行约束判断。
package recursion; import java.util.ArrayList; public class Queen8 { int[] res = new int[8]; static int count = 0; public static void main(String[] args) { Queen8 queen8 = new Queen8(); queen8.cheak(0); System.out.println(count); } //判断新加入的是否满足八皇后的要求 public boolean judge(int n){ for (int i = 0; i < n; i++) { if (res[i] == res[n] || (Math.abs(i - n)==Math.abs(res[i] - res[n]))){//判断是否在同一列或者对角线上 return false; } } return true; } public void print(){ for (int i = 0; i < 8; i++) { System.out.printf("%d",res[i]); } System.out.println(); } //递归 public void cheak(int n){ for (int i = 0; i < 8; i++) { res[n] = i; if (judge(n)){ if (n == 7){ print(); count++; }else { cheak(n+1); } } } } }