我正试图为一所大学的工作开发一些代码,我有一个算法,它给出了图中两个节点之间的最短路径。请注意,节点是有资本的国家。
有人能解释我如何发展一些东西,给我从A国到B国的最短路径,通过一份首都(国家)清单吗?
我已经实现了一种方法,它也给我两个地理点之间的距离。
我最初的想法是根据各国首都与A国之间的距离排序,然后将A国与清单第一国、第一国和第三国之间最短路径的所有距离相加,以此类推。显然这是不对的。
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;
}
谢谢。
发布于 2019-11-07 15:42:29
问题描述:
给定一个顶点V和边E的图,我们希望在Va和Vb之间找到一条路径P,这样:
伪码:
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
https://stackoverflow.com/questions/58748130
复制相似问题