首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >首都间通过其他首都的最短路径

首都间通过其他首都的最短路径
EN

Stack Overflow用户
提问于 2019-11-07 11:47:40
回答 1查看 241关注 0票数 0

我正试图为一所大学的工作开发一些代码,我有一个算法,它给出了图中两个节点之间的最短路径。请注意,节点是有资本的国家。

有人能解释我如何发展一些东西,给我从A国到B国的最短路径,通过一份首都(国家)清单吗?

我已经实现了一种方法,它也给我两个地理点之间的距离。

我最初的想法是根据各国首都与A国之间的距离排序,然后将A国与清单第一国、第一国和第三国之间最短路径的所有距离相加,以此类推。显然这是不对的。

代码语言:javascript
运行
复制
    public double shortestPathCapitals2(List<String> capitais, Pais pOrig, Pais pDest) {
    double dist = 0;
    LinkedList<Pais> shortPath = new LinkedList<Pais>();
    LinkedList<String> temp = new LinkedList<>(capitais);

    temp.addFirst(pOrig.getCapital());
    temp.addLast(pDest.getCapital());

    Collections.sort(temp, (c1, c2) -> (int) (distance(pOrig, shortestPathCapitals2(c2)) - distance(pOrig, obterPaisPorCapital(c1))));

    for (int i = 0; i < temp.size() - 1; i++) {
        Pais p1 = obterPaisPorCapital(temp.get(i));
        Pais p2 = obterPaisPorCapital(temp.get(i + 1));
        dist += shortestPath(p1, p2, shortPath);
        shortPath.clear();
    }

    return dist;
}

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-07 15:42:29

问题描述:

给定一个顶点V和边E的图,我们希望在Va和Vb之间找到一条路径P,这样:

  • 路径包含{V0,V1,.}(V的某些子集)
  • P中边的权重之和是最小

伪码:

代码语言:javascript
运行
复制
function findPath(startVertex, endVertex, verticesToBeVisited, currentPath)

    // check if we have reached the destination
    if startVertex == endVertex:

          /*
           * there are multiple ways of reaching the destination
           * calculate the length of the past (also called the cost)
           * if the cost is lower than the current minimum, store the path
           */
          cost = calculateCost(currentPath)
          if cost  < currentMinCost:
              currentMinCost = cost
              currentMinPath = currentPath            

    else:

        /*
         * if we have not reached the destination
         * we need to try all possible next hops
         * this algorithm uses recursion to do so
         */
        for every vertex Vn that is a neighbour of startVertex:

            /*
             * this check prevents us from going
             * Paris --> Rome --> Paris --> Rome (endlessly)
             */
            if currentPath contains Vn:
                 continue

            // add the next hop to our path
            currentPath += Vn

            // if this vertex needed to be visit, cross it out in the list
            if verticesToBeVisited contains Vn:
                verticesToBeVisited -= Vn

            // recursion
            findPath(Vn, endVertex, verticesToBeVisited, currentPath)

            // clean up
            if verticesToBeVisited contained Vn:
                verticesToBeVisited += Vn

            currentPath -= Vn
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58748130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档