Java 计算无向加权图中一组顶点之间的最短路径
我有一个无向加权图(G),它至少由15个顶点组成。给定一组顶点(G'),其中G'⊆ G、 我需要计算在给定起始顶点(v)的情况下穿过G'所需的最短路径。 我被卡住了! 我尝试了以下方法:Java 计算无向加权图中一组顶点之间的最短路径,java,graph,shortest-path,Java,Graph,Shortest Path,我有一个无向加权图(G),它至少由15个顶点组成。给定一组顶点(G'),其中G'⊆ G、 我需要计算在给定起始顶点(v)的情况下穿过G'所需的最短路径。 我被卡住了! 我尝试了以下方法: for (Vertex vx : G'): computeShortestPath (v, vx)//using Dijkstra's algo 在V和G'的任何顶点之间生成的所有路径中的最短路径将构成初始化路径(p)。然后,我从G'中删除在p'中访问过的所有顶点 G'.remove (P) 递归计
for (Vertex vx : G'):
computeShortestPath (v, vx)//using Dijkstra's algo
在V和G'的任何顶点之间生成的所有路径中的最短路径将构成初始化路径(p)。然后,我从G'中删除在p'中访问过的所有顶点
G'.remove (P)
递归计算p,直到:
G'.size () == 0
不过,我的算法有时似乎效率低下!对这个问题的不同补救措施有什么建议吗
编辑:我只需要访问G'中的每个节点一次 如果我正确理解了你的问题,那么它本质上就是一个被证明是NP难的问题:这个问题没有有效的解决方案。您提出的任何解决方案都需要随着节点数量呈指数增长的资源。对于返回最可能的最短路径或向最短路径迭代,存在有效的解决方案。有一些算法可以在开始搜索之前确定是否存在路径 Djikstra的算法用于通过图找到最短路径,而不是访问所有节点的最短路径 对于少量节点,最简单的解决方案是彻底搜索所有路径。这将类似于:
class PathFinder {
Path shortestPath;
public void findShortestPath(Path currentPath, List<Node> remainingNodes) {
if (remainingNodes.isEmpty()) {
if (currentPath.isShorterThan(shortestPath)) {
shortestPath = currentPath;
}
} else {
for (Node node: currentPath.possibleNextNodes(remainingNodes)) {
remainingNodes.remove(node);
currentPath.add(node);
findShortestPath(currentPath, remainingNodes);
currentPath.remove(node);
remainingNodes.add(node);
}
}
}
}
当您说“遍历G”时,“您的意思是”至少访问G'中的每个节点一次”、“访问G'中的某个节点”、“恰好访问G'中的每个节点一次”还是其他什么?@templatetypedef仅访问G'中的每个节点一次eCurrentPath。可能的ExtNodes(remainingNodes)将检索即将到来的节点的候选节点。背后的逻辑是什么?是否基于最近邻?possibleNextNodes用于返回连接到路径中最后一个节点的所有节点,而这些节点本身不在路径中。实现将取决于节点和链接的结构。我将添加一个可能的实现供您考虑。给它一个镜头,我会发布我的版本及其结果路径。Thx束
public class Node {
private class Link {
private final Node destination;
private final int weight;
private Link(Node destination, int weight) {
this.destination = destination;
this.weight = weight;
}
private final List<Link> links;
public void addLink(Node destination, int weight) {
if (!connectsTo(destination)) {
Link link = new Link(destination, weight);
destination.addLink(this, weight);
}
}
public boolean connectsTo(Node node) {
return links.stream.anyMatch(link -> link.destination.equals(node));
}
public int weightTo(Node node) {
return links.stream.filter(link -> link.destination.equals(node))
.findAny().orElse(0);
}
}
public class Path {
private int length;
private List<Node> nodes;
private Node lastNode() {
return nodes.get(nodes.size() - 1);
}
public List<Node> possibleNextNodes(List<Node> possibleNodes) {
if (nodes.isEmpty());
return possibleNodes;
return possibleNodes.stream()
.filter(node -> lastNode().connectsTo(node))
.filter(node -> !nodes.contains(node))
.collect(Collectors.toList());
}
public boolean isShorterThan(Path other) {
return this.length < other.length;
}
public void add(Node node) {
length += lastNode().distanceTo(node);
nodes.add(node);
}
}