④当得到一个正确解时,在栈回退到上一个栈时,就会开始回溯,即将第一个皇后,放到第一列的所有正确解,全部得到。
⑤然后回头继续第-一个皇后放第二列,后面继续循环执行①②③④的步骤。
/**
-
@Author: Yeman
-
@Date: 2021-10-31-15:48
-
@Description:
*/
public class Queue8 {
int max = 8; //8个皇后
int[] arr = 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种解法\n”,count);
System.out.printf(“一共判断了%d次”,judgeCount);
}
//用来放置第n个皇后
private void check(int n){
if (n == max){ //n为8相当于是第九个皇后了,说明已经全部放好了
print();
return;
}
for (int i = 0; i < arr.length; i++) {
arr[n] = i;
if (judge(n)){ //不冲突
check(

本文介绍使用Java实现递归回溯法解决八皇后问题,详细解析了放置和判断逻辑,以及代码实现过程。同时,作者分享了自己的职业经历,并提供了大厂面试题资源。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



