Java 使用递归查找长度(无Dijkstra)
仅仅因为这是一个练习递归的练习,我的教授就给出了在迷宫中找到所有解的坐标的代码。这很有意义,我将所有这些解决方案添加到Java 使用递归查找长度(无Dijkstra),java,recursion,Java,Recursion,仅仅因为这是一个练习递归的练习,我的教授就给出了在迷宫中找到所有解的坐标的代码。这很有意义,我将所有这些解决方案添加到ArrayList solutions中,现在我想在递归之外为创建一个for循环,遍历列表,找到坐标的最小长度,并相应地更新,就像找到ArrayList的最小整数一样 但是,它将空的ArrayLists,添加到ArrayList solutions,因此,当我尝试获取第一个元素时,它将与空元素进行比较,因此找不到最短的长度。有人知道如何获取解决方案并将其添加到我的ArrayLis
ArrayList solutions
中,现在我想在递归之外为创建一个for
循环,遍历列表,找到坐标的最小长度,并相应地更新,就像找到ArrayList
的最小整数一样
但是,它将空的ArrayLists
,添加到ArrayList solutions
,因此,当我尝试获取第一个元素时,它将与空元素进行比较,因此找不到最短的长度。有人知道如何获取解决方案并将其添加到我的ArrayList
这是给我的递归代码:
else{
ArrayList<ArrayList<Coord>> solutions = new ArrayList<Array List<Coord>>();
for(int i=0; i<directions.length; i++){
Coord nextSpot = currentSpot.addTo(directions[i]);e
if(nextSpot.validSpot(maze))
if(!newPath.contains(nextSpot)){
ArrayList<Coord> solution = //The recursive call
solve(newPath,nextSpot,goal,maze);
if(solution != null)
{
solutions.add(solution);
}
}//ifs
}//for
else{
ArrayList solutions=新的ArrayList();
对于(int i=0;i
ArrayList<Coord> smallestPath = (ArrayList<Coord>)solutions.get(0);
ArrayList currentPath = new ArrayList();
for(int i = 0; i < solutions.size(); i++){
currentPath = (ArrayList)solutions.get(i);
if(currentPath.size() < smallestPath.size()){
smallestPath = currentPath;
}
System.out.println("currentPath is : " + currentPath);
}
return smallestPath;
}//else (recursive case)