如何解决我如何不使用System.exit0来停止回溯?
|static void Lasvegas(int []tablero,int f,int ultimaReina){
HashSet<Integer> enterosUsados = new HashSet<Integer>();
if (ultimaReina!=-1) enterosUsados.add(ultimaReina);
if ((ultimaReina-1) >=0){enterosUsados.add(ultimaReina-1);}
if ((ultimaReina+1 != tablero.length) && (ultimaReina!=-1)){enterosUsados.add(ultimaReina+1);}
// if(ultimaReina+1!=tablero.length){enterosUsados.add(ultimaReina+1);}
Random random = new Random();
int posReina;
if (f==tablero.length){
printBoard(tablero);
stop=System.currentTimeMillis();
System.out.println(stop-start);
System.exit(0);
return;
}
do {
do{
posReina= Math.abs(random.nextInt())%tablero.length;
}
while(enterosUsados.add(posReina)==false);
tablero[f]=posReina;
if (check(tablero,f)){
Lasvegas(tablero,f+1,posReina);
}
} while (enterosUsados.size()<tablero.length);
}
public static void main(String[] args) {
// testChicuadrado(410,30);
int [] tablero = new int[8];
Arrays.fill(tablero,-1);
start = System.currentTimeMillis();
Lasvegas(tablero,-1);
}
static boolean check (int [] array,int f){
for (int i=0; i<f; i++){
if (array[i]==array[f]) return false;
if( Math.abs(array[f]-array[i])== Math.abs(f-i)) return false;
} return true;
}
static void printBoard(int [] tablero) {
char [] linea = new char[tablero.length];
Arrays.fill(linea,\'*\');
for (int i=0;i<tablero.length;i++){
linea[tablero[i]]=\'D\';
System.out.println(new String(linea));
linea[tablero[i]]=\'*\';
}
}
我正在使用拉斯维加斯算法在板上生成随机的女王位置,我想通过多次运行对其进行计时,但是如果找到解决方案,我将使用System.exit(0)
停止回溯,如果我不要止步于此,我的算法还提供了其他我不想要的解决方案。
这里:
if (f==tablero.length){
printBoard(tablero);
stop=System.currentTimeMillis();
System.out.println(stop-start);
System.exit(0);
return;
}
如何更改它并使算法在没有System.exit(0)
的情况下停止,以便可以在循环中多次调用它?
解决方法
将返回类型
LasVegas
更改为boolean
。删除对System.exit()
的调用,并将紧随其后的return;
语句更改为return true;
。将递归调用更改为:
if (LasVegas(tablero,f+1,posReina)) return true;
, 您可以使函数返回布尔值
static bool LasVegas( ...
而不是Exit
返回false
。在其他情况下,返回true
。
同样,当递归调用函数时,只需检查结果,如果为false,则返回false:
if (check(tablero,f)){
if (!LasVegas(tablero,posReina))
return false;
}
, 用出口代替出口;
在while循环中,您可以调用break;退出
, 我在这里有一个很好的建议:
如果您已经完成回溯,并且不想继续。
创建一个静态或虚拟变量(布尔或整数)
完成后,为其分配一些值(说“ true”或“ 1”)
在Backtrack方法和\'return \'中检查伪变量值。
如果(完成)返回; //在这里,所有的backtrack方法将只返回true到被调用的方法,而不执行任何操作。重要的是这段代码应该在回溯方法的开头。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。