我在使用递归 Java 程序时遇到了问题,目前的问题是我不明白为什么 base case1 if 正在执行。在对 findPath 的初始方法调用中,传递了值 2 和 0。exitRow = 4 和 cols-1 = 11。所以,我的理解是这个基本情况不应该首先进入 if 语句,因为 maze[][] 中的两个位置不一样(maze[4][11] ! =迷宫[2][0])。但这正是它正在做的事情。我显然在对 if 结构的理解中遗漏了一些东西,或者我在其他地方有错误,希望能得到一些帮助。
注意:我也试过
if (row == exitRow && col == cols-1)
但这最终给了我一个堆栈溢出。从我对此知之甚少的情况来看,这意味着要么我的递归没有让我更接近基本案例,要么基本案例由于其编写方式而无法访问。根据我一直在使用的本指南http://www.cs.bu.edu/teaching/alg/maze/ ,我假设我的递归是正确的。这使我相信基本情况是问题所在。
非常感谢。
private Boolean findPath(int row, int col)
{
//base case 1
if (maze[exitRow][cols-1]==maze[row][col])
{
System.out.println("test");//for debugging
return true;
}
//base case 2
if (maze[row][col] == '#')
{
return false;
}
maze[row][col] = 'O';
System.out.println("test1");//for debugging
steps++;
//check north
if (findPath(row+1,col)==true )
{
return true;
}
//check east
if (findPath(row,col+1)==true )
{
System.out.println("test2");
return true;
}
//check south
if (findPath(row-1,col)== true)
{
return true;
}
//check west
if (findPath(row,col-1)== true)
{
return true;
}
System.out.println(steps);
maze[row][col] = '.';//unmark location
return false;
}