【发布时间】:2021-04-27 19:49:03
【问题描述】:
我的代码一直存在问题,我的递归方法突然停止遍历我设置的迷宫,原因我无法确定。我的迷宫存储在一个二维数组中,其中 1 被视为墙壁,0 被视为路径。我的代码总是从坐标 (0, 1) 开始。
public int[][] mazeSearch(int xCoord, int yCoord, int[][] mazeGrid, int counter){
//the current coordinates
String currentPosition = "(" + xCoord + ", " + yCoord + ")";
//if the maze position is part of the pathway...
if(mazeGrid[yCoord][xCoord] == 0){
//BASE CASES
//check if we are on the right edge of the board
if(xCoord == mazeGrid.length - 1 && mazeGrid[yCoord][xCoord] != 2 && counter != 0) {
System.out.println(currentPosition);
return mazeGrid;
}
if(xCoord == mazeGrid.length + 1 && mazeGrid[yCoord][xCoord] != 2 && counter != 0) {
System.out.println(currentPosition);
return mazeGrid;
}
//check if we are on the left edge of the board
if(yCoord == mazeGrid[yCoord].length - 1 && mazeGrid[yCoord][xCoord] != 2 && counter != 0) {
System.out.println(currentPosition);
return mazeGrid;
}
//check if we are on the
if(yCoord == mazeGrid[yCoord].length + 1 && mazeGrid[yCoord][xCoord] != 2 && counter != 0) {
System.out.println(currentPosition);
return mazeGrid;
}
//////
//a 2 is placed in this spot to indicate the path that has been taken
mazeGrid[yCoord][xCoord] = 2;
//////
//this goes through the maze and checks the areas around the current coordinate
if(mazeGrid[yCoord][xCoord + 1] == 0){
return mazeSearch(xCoord + 1, yCoord, mazeGrid, counter + 1);
}else if(mazeGrid[yCoord + 1][xCoord] == 0){
return mazeSearch(xCoord, yCoord + 1, mazeGrid, counter + 1);
}else if(mazeGrid[yCoord][xCoord - 1] == 0){
return mazeSearch(xCoord - 1, yCoord, mazeGrid, counter + 1);
}else{
return mazeSearch(xCoord, yCoord - 1, mazeGrid, counter + 1);
}
}
return mazeSearch(xCoord, yCoord, mazeGrid, counter);
}
计数器自动为 0 并且存在,因此我的代码不会在开头结束。
这是未标记的迷宫的样子:
1111111
0000000
1111111
这是方法完成后控制台打印出来的内容:
1111111
2200000
1111111
我的代码中是否存在过早停止该方法的内容?还是我没有说明情况?对不起,我还在学习递归,比我预期的要难。
【问题讨论】:
标签: java recursion path-finding