我试图在使用递归的迷宫中找到最小的路径大小。要做到这一点,迷宫必须穿过所有可能的路径,然后不断更新"最短长度"。
我可以让它浏览所有可能的列表,并打印这些坐标和路径大小,但我无法找到最小值,因为最后找到的路径总是更新为"最短长度"。
因此,我想将所有的解决方案路径长度添加到ArrayList<Integer> list
中,然后在递归求解方法之外创建一个单独的静态类,在那里我找到最小值,并将其值返回给solve()
方法,然后从那里继续。这是做这件事的最佳方式吗?或者我可以在solve()
方法中找到最短的长度和相应的坐标吗?
这是递归情况下的代码:
else {
for(int i = 0; i < directions.length; i++)
{
Coord nextSpot = currentSpot.addTo(directions[i]);
if(nextSpot.validSpot(maze))
if(!newPath.contains(nextSpot)){
ArrayList<Coord> solution = //The recursive call
solve(newPath,nextSpot,goal,maze);
if(solution != null){
int shortestLength = 100; //arbitrary large length
// lengths.add(lengthSolution); ?? Possible alternative?
System.out.println(lengthSolution);
System.out.println(solution);
if( solution.size() < shortestLength ){
shortestLength = solution.size();
System.out.println(shortestLength);
}
}
}//ifs
}//for
return null;
}//else (recursive case)
int globalsteps =0;
int maze(x,y,steps) {
if(icangoup){ maze(x+1,y,steps +1);}
if(icangodown){ maze(x-1,y,steps +1);}
if(icangoleft){ maze(x,y+1,steps +1);}
if(icangoright){ maze(x,y-1,steps +1);}
if(ifoundtheexit!!!!) {
if(globalsteps == 0 || steps < globalsteps)
globalsteps = steps;
}
}
}