因此,我一直在這方面努力,只是似乎無法解決這個問題。我有一個列有開始城市和目標城市的「道路」列表。通過遞歸,我必須找到所有可能的路線。我目前的代碼只找到最長的路線。 我能做些什麼來解決這個問題?通過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