首先先说一下我理解的递归回溯:
执行某个方法时
会先将方法中已执行的语句入栈
当递归调用时重新开一个栈
当递归结束回到这个方法时
继续执行接下来的操作
这个就是回溯了
先上代码,然后再说说要注意的点
public class Queue {
//八皇后问题
private int EIGHT = 8;//n皇后
private int[] chessboard;//用一维数组来存储皇后位置
private int count = 1;//记录解法
Queue(){
chessboard = new int[EIGHT];//初始化
put(0);//从第一个皇后开始放
}
private void put(int n){
if(n == EIGHT)//如果n==8说明是第九个皇后,之前的八个摆放合理
{
print();//输出八皇后坐标信息
return;
}
for(int i = 0;i<EIGHT;i++)
{
chessboard[n] = i;//每一格都放一次皇后
if(judge(n))
{
put(n+1);//摆放下一个皇后
}
}
}
private boolean judge(int n){//判断是否摆放合理
for(int i = 0;i<n;i++)
{
//chessboard[i]==chessboard[n]说明同列
//(n-i)==Math.abs(chessboard[i]-chessboard[n])说明同斜线
if(chessboard[i]==chessboard[n]||(n-i)==Math.abs(chessboard[i]-chessboard[n]))
return false;
}
return true;
}
private void print(){
System.out.print(count+" ");
count++;
for(int chess:chessboard)
{
System.out.print(chess+" ");
}
System.out.println();
}
}
1.一维数组
用一维数组代替二维数组,这个减少遍历,而且不浪费存储空间
下标代表行
值代表列
2.判断斜线
(n-i)==Math.abs(chessboard[i]-chessboard[n])说明同斜线
这个的由来就是当横行减竖行相等时就代表是同斜线了
669

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



