因为你的方法已经不适合find_routes(source, destination)我认为这没关系添加另一个参数find_routes(source, destination, currentRoute)。
首先你必须定义“静态结构”是写在你的问题。那些会是这样的:
private static String[] sourceArray = {"Seattle", "LA", "LA", "Florida", "Seattle"};
private static String[] destinationArray = {"LA", "Florida", "Maine", "Seattle", "Florida"};
那么当然这是一个递归问题。所以你必须找到递归锚点。在继续阅读之前花一点时间思考一下。
递归锚很明显是源与目的地相同。
所以在找到递归锚后,您只需添加后续步骤即可。您将相应的目的地作为新来源的想法已经是正确的方法。 你不做的是保存这些后续步骤。
为此我使用第三个参数:currentRoute。它被初始化为一个空列表并且总是用当前节点扩展。如果我们结束了递归锚点,我们可以将我们当前的路线添加到路线列表。
如果我们不在递归锚,我们也必须检查周期。为了避免这些,我们可以在currentRoute中查看当前节点是否已经在里面。请注意,对于庞大的数据集,您现在仍然可以达到堆栈限制,因此需要一些额外的助手(例如,中断深度)。
package sto;
import java.util.ArrayList;
public class PathFinding {
private static ArrayList> routes = new ArrayList>();
private static String[] sourceArray = {"Seattle", "LA", "LA", "Florida", "Seattle"};
private static String[] destinationArray = {"LA", "Florida", "Maine", "Seattle", "Florida"};
public static void main(String rgs[])
{
find_routes("Seattle", "Maine", new ArrayList());
for(ArrayList route : routes) {
for(String node : route) {
System.out.print(node + ", ");
}
System.out.println();
}
}
private static void find_routes(String source, String destination, ArrayList currentRoute) {
// copy current route and add current node
ArrayList newRoute = new ArrayList();
newRoute.addAll(currentRoute);
newRoute.add(source);
// recursion anchor: source is destination, so route is finished and can be added to our routes
if(source.equals(destination)) {
routes.add(newRoute);
} else {
// check all possibilities for other routes
for(int i = 0; i < sourceArray.length; ++i) {
if(source.equals(sourceArray[i])) {
// if node is already in our route: cycle, i.e. no solution or no optimal solution
if(!currentRoute.contains(source)) {
find_routes(destinationArray[i], destination, newRoute);
}
}
}
}
}
}
这绝对不是最有效的方法,但它应该给你一个提示如何去做。