gpt4 book ai didi

java - 这段示例代码中哪里发生了回溯?

转载 作者:行者123 更新时间:2023-11-30 06:15:53 25 4
gpt4 key购买 nike

package maze;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

public class Maze {


public static void main(String[] args) {
int board[][] = new int[31][121];
Random rand = new Random();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
board[i][j]=1;
}
}
int r = rand.nextInt(board.length);
while(r%2==0){
r=rand.nextInt(board.length);
}

int c = rand.nextInt(board[0].length);
while(c%2==0){
c=rand.nextInt(21);
}
System.out.format("r is %d and c is %d\n",r,c);
board[r][c]=0;
recursion(r,c,board);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j]==1) {
System.out.print("#");
} else if (board[i][j]==0) {
System.out.print(" ");
}

}
System.out.println("");
}

}
public static void recursion(int r, int c,int[][] board){
ArrayList<Integer> randDirections = generateDirections();
int[] randDir=new int[randDirections.size()];

for (int i = 0; i < randDir.length; i++) {
randDir[i]=randDirections.get(i);
System.out.println(randDir[i]);
}

for (int i = 0; i < randDir.length; i++) {

switch(randDir[i]){
case 1:
//checks up position
if (r-2>=0) {
if (board[r-2][c]!=0) {
board[r-2][c] = 0;
board[r-1][c] = 0;
recursion(r - 2, c,board);
}
}
break;
case 2:
//checks right position
if (c + 2 <= board[0].length - 1){
if (board[r][c + 2] != 0) {
board[r][c + 2] = 0;
board[r][c + 1] = 0;
recursion(r, c + 2,board);
}
}
break;
case 3:
//checks down position
if (r + 2 <= board.length - 1){
if (board[r + 2][c] != 0) {
board[r+2][c] = 0;
board[r+1][c] = 0;
recursion(r + 2, c,board);
}
}
break;
case 4:
//checks left position
if (c - 2 >= 0){
if (board[r][c - 2] != 0) {
board[r][c - 2] = 0;
board[r][c - 1] = 0;
recursion(r, c - 2,board);
}
}
break;
}
}
}
public static ArrayList<Integer> generateDirections(){
ArrayList<Integer> randoms = new ArrayList();
for (int i = 0; i < 4; i++) {
randoms.add(i+1);
}
Collections.shuffle(randoms);
return randoms;
}
}

我可以看到,当我的程序无法为我的迷宫创建另一条路径时,它正在回溯,并且我的递归方法仅在它一路回溯回到第一个路径方 block 时才会停止。但是,我不知道到底是做什么的。在我看来,当四个随机方向的 for 循环耗尽时,该方法应该停止。有人可以向我解释哪部分代码导致它回溯以及它是如何工作的吗?

最佳答案

答案在于调用堆栈并了解堆栈每一层发生的情况。当一个递归调用耗尽其 for 循环时,就会发生“回溯”,此后,该方法返回,从堆栈中弹出一层,并继续执行调用的堆栈级别上下文的 for 循环。

仅绘制出 2 个级别的调用可以帮助澄清。您会发现在第一个“级别”(递归的根调用)中,for 循环只是按照您的预期进行迭代,但是它将散布在其进行的递归调用的处理中(每个创建一个“下一个级别”的递归)。

调用堆栈底层的 for 循环会执行所有迭代,而上层的 for 循环可能只进行第一次迭代。

关于java - 这段示例代码中哪里发生了回溯?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49202973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com