【发布时间】:2018-03-09 22:13:06
【问题描述】:
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;
}
}
我可以看到,当我的程序无法为我的迷宫开辟另一条路径时,我的程序正在回溯,并且我的递归方法只有在它一直回溯到第一个路径方格时才会停止。但是,我不知道到底是在做什么。在我看来,当四个随机方向的 for 循环用尽时,该方法应该停止。有人可以向我解释哪部分代码导致它回溯以及它是如何工作的吗?
【问题讨论】:
-
感谢您向我展示该视频。但是,我仍然不明白他展示的堆栈和条件部分是如何存在于我的程序中的。你能告诉我我的程序是如何做同样的事情的吗?
-
您还想要答案吗?
-
是的,任何你能帮助解释回溯发生的地方都会很棒。我想我误解了递归的工作方式。
标签: java recursion backtracking maze