编辑 有人向我指出,实际上我需要逐步执行所有递归,以确保到达终点,然后当我返回堆栈时开始收集值。我不知道这意味着什么。
我的目标是构建一个递归方法来构建一条穿过迷宫的路径,将该路径存储在 Vector 中,并在递归结束时返回它。
我的方法运行迷宫,但我在将列表存储在 Vector 中时遇到困难,因为我需要每次递归都实例化它。
这是我的代码(编辑):
protected Vector<GameCell> findPath(int nRow, int nCol)
{
aBoard[nRow][nCol].setVisited(true);
if(aBoard[nRow][nCol].getVal() == 'E')
{
Vector<GameCell> list = new Vector<GameCell>();
list.add(aBoard[nRow][nCol]);
return list;
}
if(canGoLeft(nRow, nCol))
{
if(!aBoard[nRow][nCol - 1].isVisited())
{
return findPath(nRow, --nCol);
}
}
if(canGoRight(nRow, nCol))
{
if(!aBoard[nRow][nCol+1].isVisited())
{
return findPath(nRow, ++nCol);
}
}
if(canGoUp(nRow, nCol))
{
if(!aBoard[nRow - 1][nCol].isVisited())
{
return findPath(--nRow, nCol);
}
}
if(canGoDown(nRow, nCol))
{
if(!aBoard[nRow + 1][nCol].isVisited())
{
return findPath(++nRow, nCol);
}
}
System.out.println("You hit a dead end.");
return null;
}
有没有办法让我不能每次递归都实例化我的 vector ,以便我可以永久存储我的值?
任何帮助将不胜感激。
最佳答案
典型的方法是委托(delegate)给另一种递归方法,并以要填充的列表作为参数:
public List<GameCell> findPath(int nRow, int nCol) {
List<GameCell> result = new ArrayList<>();
doFindPathRecursively(result, nRow, nCol);
return result;
}
private void doFindPathRecursively(List<GameCell> result, int nRow, int nCol) {
...
}
请注意,自 Java 2 以来,Vector 实际上已被弃用,因此改用 List 和 ArrayList。
关于java - 在 Java 中的递归方法中创建 vector 并存储信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42235564/