【问题标题】:Travelling salesman (TSP) getting the actual path旅行推销员 (TSP) 获取实际路径
【发布时间】:2017-03-26 10:51:04
【问题描述】:

我想知道是否有一种方法可以在我的解决方案中获取蛮力算法 (TSP) 选择的路径(不仅是距离),就像我只得到距离一样。

请注意,我从 City Stockholm 开始,到 Stockholm 结束。

  • 最短路径是city1 --> City2 --> City3 ----> .......然后---> City1 ?

我的主要课程的一部分:

    public void step(boolean[] wentTo, int currentCity, float distance)
    {
        int wentToCount = 0;
        for (int i = 1; i <= cityCount; ++i)
        {
            if (wentTo[i - 1])
            {
                ++wentToCount;
                continue;
            }
            boolean[] copy = new boolean[cityCount];
            System.arraycopy(wentTo, 0, copy, 0, cityCount);
            copy[i - 1] = true;
            float dist = distance + distances[distanceIndex(currentCity, i)];
            step(copy, i, dist);
        }
        if (wentToCount == cityCount)
        {
            if (shortest > distance)
            {
                shortest = distance;
            }
        }
    }

【问题讨论】:

  • 这不只是在计算中注册变量的问题吗?如果您的算法稍后决定另一条路线,则重置。
  • @OleV.V.请在代码中显示它吗?

标签: java algorithm brute-force traveling-salesman


【解决方案1】:

最简单的部分:只需注册计算中正在进行的变量即可。如果您的算法稍后决定另一条路线,则重置。对于不了解您的代码的局外人来说,困难的部分是尝试将其融入到充其量难以理解的代码中。尽管如此,这是一个尝试。为了记录路线,我使用了两个实例变量:

/** stack of numbers of towns on the route so far */ 
private Deque<Integer> route = new ArrayDeque<>();
/** shortest route found */
private List<Integer> solution;

要保持第一次更新,请在递归调用之前和之后执行此操作:

        route.push(i);
        step(copy, i, dist);
        // after having tried town i, remove it from route again before trying next town
        int j = route.pop();
        assert j == i : "Got wrong town off stack, " + j + " instead of " + i;

这将确保在您将所有城镇添加到路线后,它们也会以正确的顺序出现在 route 堆栈中。

要使solution 保持最新状态,请在找到较短路线时为其添加新值:

        if (shortest > distance)
        {
            shortest = distance;
            solution = new ArrayList<>(route);
        }

现在,当您打印出最短距离时,您的solution 会保存访问过的城镇的顺序,因此您也可以打印它。

由于我没有你的完整代码,我没有机会测试,所以可能需要在这里和那里进行打磨。

【讨论】:

  • 添加 private Deque route = new ArrayDeque() 后出现错误;我在我的项目下面的主帖子中添加了我的实际项目,请看一下
  • 你需要导入java.util.ArrayDeque和java.util.Deque。您收到什么错误消息?
  • 我不明白这个“在你的递归调用之前和之后做这个”,当我打印出来时路由是空的?
  • 您是否尝试打印route 或solution? route 应该是空的。 solution 不应该。
猜你喜欢
  • 2015-06-22
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
相关资源
最近更新 更多