# 八皇后问题百度解法的缓存没弄明白

``````
public class Queener {
private int[] column; //同栏是否有皇后，1表示有
// 是否在一条斜线
private int[] rup; //右上至左下是否有皇后
private int[] lup; //左上至右下是否有皇后

private int[] queen; //解答
private int num; //解答编号(第几种答案)
private static final int maxCount = 8;

public Queener() {
column = new int[maxCount ];
queen = new int[maxCount];

rup = new int[2 *maxCount  ];
lup = new int[2 * maxCount];
for (int i = 0; i < maxCount; i++)
column[i] = 0;
for (int i = 0; i < (2 * maxCount); i++)
rup[i] = lup[i] = 0;  //初始定义全部无皇后

}

public void backtrack(int i) {
if (i == maxCount) {
} else {
for (int j = 0; j < maxCount; j++) {
if ((column[j] == 0) && (rup[i + j] == 0) && (lup[i - j + maxCount] == 0)) {
//若无皇后
queen[i] = j; //设定为占用
column[j] = rup[i + j] = lup[i - j + maxCount] = 1;
backtrack(i + 1);  //循环调用
column[j] = rup[i + j] = lup[i - j + maxCount] = 0;
}
}
}
}

num++;
System.out.println("\n解答" + num);
for (int y = 0; y < maxCount; y++) {
for (int x = 0; x < maxCount; x++) {
if (queen[y] == x) {
System.out.print("Q");
} else {
System.out.print(".");
}
}
System.out.println();
}
}

public static void main(String[] args) {
long start = System.currentTimeMillis();
Queener queen = new Queener();
queen.backtrack(0);
System.out.println("耗时:" + (System.currentTimeMillis() - start));
}
}``````

1 个回答

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进