java中 求路段的平均旅行时间_Java中的旅行路线

因为你的方法已经不适合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);

}

}

}

}

}

}

这绝对不是最有效的方法,但它应该给你一个提示如何去做。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值