package dfs;
import java.util.*;
public class 八皇后3 {
static int ans[][] = new int[6][6];
static int lie[] = new int[6];
static int hang[] = new int[6];
static int c[] = new int[20];
static int d[] = new int[20];
static int ans2 = 0,count = 0;
public static void main(String[] args) {
dfs(0,0);
System.out.println(count);
}
static void dfs(int x,int y){
count++;
if (y > 5) {
y = 0;
x++;
}
if (x == 6 || ans2 != x) {//这里加上这句ans2 != x可以少递归十倍
if (ans2 == 6) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
System.out.print(ans[i][j] + " ");
}
System.out.println();
}
System.out.println("**************");
}
return;
}
//不放皇后
dfs(x,y + 1);
//放皇后
if(lie[x] == 0 && hang[y] == 0 && c[x + y] == 0 && d[y -x + 6] == 0){
lie[x] = 1;
hang[y] = 1;
c[x + y] = 1;
d[y - x + 6] = 1;
ans[x][y] = 6;
ans2++;
dfs(x + 1,0);
lie[x] = 0;
hang[y] = 0;
c[x + y] = 0;
d[y - x + 6] = 0;
ans[x][y] = 0;
ans2--;
}
}
}
这里我直接测试棋盘大小为6时的数据
主要是每次除了最后一行数据不符合要求时,其他的都不会回溯,会接着去递归下面的数据,但是当这一行没有符合要求的空位时,按理来说是不可能为正确答案了,此时就可以回溯了,一旦程序接着往下一行走,就会导致ans2与x不相等,此刻就结束此轮递归,直接return