【发布时间】:2015-03-02 10:14:17
【问题描述】:
所以我已经为此工作了很长时间,但似乎无法解决这个问题。我有一个包含 startCity 和 goalCity 的“道路”列表。通过递归,我必须找到所有可能的路线。我当前的代码只能找到最长的路线。 我该怎么做才能解决这个问题?
道路:
Colorado Springs,Denver
Denver,Loveland
Loveland,Fort Collins
Loveland,Greeley
Greeley,Fort Collins
Fort Collins,Cheyenne
Fort Collins,Laramie
Laramie,Cheyenne
电流输出:
All paths from Colorado Springs to Fort Collins are:
1. [Colorado Springs, Denver, Loveland, Fort Collins]
2. [Colorado Springs, Denver, Loveland, Greeley, Fort Collins]
3. [Colorado Springs, Denver, Loveland, Greeley, Fort Collins, Loveland, Greeley, Fort Collins]
编辑更新代码: 现在我得到了额外的输出......
public ArrayList<String> findPath2(String startCity, String goalCity, String oStartCity, ArrayList<String> route){
//see if goal city possible
if(tester(goalCity) != true){
return null;
}
///Base Case////
if(startCity.equals(goalCity)){
route.add(goalCity);
String derp = route.toString();
paths.add(derp);
System.out.println(derp);
//return route;
}else{
for (int i = 0; i < theRoads.size(); i ++){
if(theRoads.get(i).isFrom(startCity)){
route.add(startCity);
findPath2(theRoads.get(i).endsAt(), goalCity, oStartCity, route);
//System.out.println(route);
//course = startCity + " -> " + course;
for (int l = i+1; l < theRoads.size(); l ++){
if(theRoads.get(l).isFrom(startCity) && !(theRoads.get(l).startsAt().equals(goalCity))){
System.out.println("SPLIT");
route.remove(goalCity);
findPath2(theRoads.get(l).endsAt(), goalCity, oStartCity, route);
System.out.println("SPLIT RETURNING");
}
}
//return route;
}
}
}
return route;
}
如果有人感兴趣,还有我的所有代码: http://pastebin.com/3yeBU2fn
第二次编辑:@Vandale
仍然无法让它工作,但是像这样?
public ArrayList<String> findPath2(String startCity, String goalCity, ArrayList<String> route){
ArrayList<String> course = new ArrayList<>();
if(startCity.equals(goalCity)){
course.add(startCity);
}else{
route.add(startCity);
for (int i = 0; i < theRoads.size(); i ++){
if(theRoads.get(i).isFrom(startCity)){
for (int l = 0; l < route.size(); l ++){
//check if city has already been visited && if its possible to get to goal city (not sure if this works)
if(!(route.get(l).equals(startCity)) && (findPath2(theRoads.get(l).endsAt(), goalCity, route).equals(goalCity))){
course.add(startCity + "->" + findPath2(theRoads.get(l).endsAt(), goalCity, route));
}
}
}
}
route.remove(startCity);
}
System.out.println(course);
return course;
}
感谢您的帮助!
【问题讨论】:
-
return "null";好像有点奇怪——你真的要返回一个字符串吗? -
对于初学者,您需要返回
List<String>,而不是String。 -
是的,我不是故意的,但显然是双向的。
-
为什么需要使用递归?这可能不是最有效的方法。
-
@Koen 你找不到最长的路径,也找不到所有没有递归模拟的路径。