因此,我一直在这方面努力,只是似乎无法解决这个问题。我有一个列有开始城市和目标城市的“道路”列表。通过递归,我必须找到所有可能的路线。我目前的代码只找到最长的路线。 我能做些什么来解决这个问题?通过reccursion找到所有可能的路线
道路:
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
2ND编辑:@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”;'似乎有点奇怪 - 你真的想返回一个字符串吗? – maja 2015-03-02 10:18:49
对于初学者,你将需要返回'List',而不是'String'。 –
amit
2015-03-02 10:20:57
是的,我不是故意这样做,显然是双向的。 – Damoclyes 2015-03-02 10:22:03