分析 :
从上往下依次放入皇后,可以成功放满n个皇后,count++
下一个无法放,则撤销一个,尝试,若仍然通再撤回,以此类推
将n的值可以改变来控制皇后的数量
public class Main {
public static int N = 8;
public static int count = 0;
public static boolean falgy[] = new boolean[N + 1];
public static boolean falgxy[] = new boolean[N + 1 + N + N];
public static void main(String[] args) {
dfs(1);
long start = System.currentTimeMillis();
System.out.println(count);
long end = System.currentTimeMillis();
System.out.println("花费时间:" + (end - start) + "ms");
}
private static void dfs(int x) {
//跳出条件
if(x == N + 1) {
count ++;
}
//选择下一步
for(int i = 1; i <= N; i ++) {
int t1 = x + i + N;
int t2 = x - i + N;
if(!falgy[i] && !falgxy[t1] && !falgxy[t2]) {
falgy[i] = true;
falgxy[t1] = true;
falgxy[t2] = true;
dfs(x + 1);
falgy[i] = false;
falgxy[t1] = false;
falgxy[t2] = false;
}
}
}
}
运行结果:
10
花费时间:0ms