因此,我正在编写一个程序,让一个人在地铁系统中从一个车站到另一个车站。我的想法是:
,
它给了我无法解决的堆栈溢出。试图进行调试,但没有结果。
public ArrayList<Station> findRoutesBetween(Station start, Station target) {
ArrayList<Station> path = new ArrayList<Station>();
for (Route route : findRoutes(start)) {
ArrayList<Station> stops = route.getStops();
boolean sameRoute = findRoutes(target).contains(route);
int stopIdstart = stops.indexOf(start);
int stopIdtarget = stops.indexOf(target);
if (sameRoute && stops.contains(start)) {
if (stopIdtarget > stopIdstart) {
path.addAll((stops.subList(stopIdstart, stopIdtarget + 1)));
return path;
} else {
List<Station> temp = stops.subList(stopIdstart, stopIdtarget + 1);
Collections.reverse(temp);
path.addAll(temp);
return path;
}
} else {
if (stopIdstart != stops.size() - 1) {
System.out.println("hh");
ArrayList<Station> t = findRoutesBetween(stops.get(stopIdstart + 1), target);
System.out.println(t.toString());
}
if (stopIdstart != 0) {
System.out.println("hh");
ArrayList<Station> t = findRoutesBetween(stops.get(stopIdstart - 1), target);
System.out.println(t.toString());
}
}
}
return path;
}函数findroutes()只返回停止所在的所有行。
发布于 2019-11-30 10:40:27
您的实现不会忽略您已经检查或正在进行的站点。这意味着,在某一时刻,你可以通过一条给定的路线从A站到B站。然后,当你在B站时,你检查所有可能的车站,然后再次看到A站。然后你又回到了A站,重新开始,再次找到B站。现在,您将在这些站点之间来回跳到没完没了的递归方法调用中,直到得到一个StackOverflowError。
保存您已经检查过的站点的列表,当它们在列表中时不要再次检查它们。所以你得到了这样的东西:
好的,我在K站,根据现有的路线,我看到了R,G,W,Z,C,I和L站。然而,我跳过了W,Z和C站,因为我已经在那里了。接下来我们只检查R,G,I和L站.
出于调试目的,您可以打印进入方法中的参数(或来自Station对象的一些数据,如站点名称)。这样,您可能已经注意到,您看到相同的电台重复自己的方法。
https://stackoverflow.com/questions/59113291
复制相似问题