Java 如何在图形的边缘中包含权重?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20246409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to include weight in edge of graph?
提问by user3025494
I want to include weights or costs of the edge on my graph using this jgrapht interface-class:
我想使用这个 jgrapht 接口类在我的图形上包含边的权重或成本:
package org.jgrapht;
public interface WeightedGraph<V extends Object, E extends Object> extends Graph<V, E> {
public static final double DEFAULT_EDGE_WEIGHT = 1.0;
public void setEdgeWeight(E e, double d);
}
回答by Plo_Koon
Yo have described Interface WeightedGraph<V,E>from here.
哟已经Interface WeightedGraph<V,E>从这里描述了。
You need to use SimpleDirectedWeightedGraphto set the weights of its edges.
Look at this example, it creates Directed Weighted Graphby using graph.addVertex(), graph.setEdgeWeight()methods and considers
shortest path between some edges by using Dijkstra Algorithmimplemented in DijkstraShortestPath.findPathBetween()method.
您需要使用SimpleDirectedWeightedGraph来设置其边缘的权重。看这个例子,它使用,方法创建有向加权图,并使用 方法中实现的Dijkstra 算法考虑某些边之间的最短路径。graph.addVertex()graph.setEdgeWeight()DijkstraShortestPath.findPathBetween()
import org.jgrapht.*;
import org.jgrapht.alg.*;
import org.jgrapht.graph.*;
import java.util.List;
public class Graph {
public static void main(String args[]) {
SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> graph =
new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>
(DefaultWeightedEdge.class);
graph.addVertex("vertex1");
graph.addVertex("vertex2");
graph.addVertex("vertex3");
graph.addVertex("vertex4");
graph.addVertex("vertex5");
DefaultWeightedEdge e1 = graph.addEdge("vertex1", "vertex2");
graph.setEdgeWeight(e1, 5);
DefaultWeightedEdge e2 = graph.addEdge("vertex2", "vertex3");
graph.setEdgeWeight(e2, 3);
DefaultWeightedEdge e3 = graph.addEdge("vertex4", "vertex5");
graph.setEdgeWeight(e3, 6);
DefaultWeightedEdge e4 = graph.addEdge("vertex2", "vertex4");
graph.setEdgeWeight(e4, 2);
DefaultWeightedEdge e5 = graph.addEdge("vertex5", "vertex4");
graph.setEdgeWeight(e5, 4);
DefaultWeightedEdge e6 = graph.addEdge("vertex2", "vertex5");
graph.setEdgeWeight(e6, 9);
DefaultWeightedEdge e7 = graph.addEdge("vertex4", "vertex1");
graph.setEdgeWeight(e7, 7);
DefaultWeightedEdge e8 = graph.addEdge("vertex3", "vertex2");
graph.setEdgeWeight(e8, 2);
DefaultWeightedEdge e9 = graph.addEdge("vertex1", "vertex3");
graph.setEdgeWeight(e9, 10);
DefaultWeightedEdge e10 = graph.addEdge("vertex3", "vertex5");
graph.setEdgeWeight(e10, 1);
System.out.println("Shortest path from vertex1 to vertex5:");
List shortest_path = DijkstraShortestPath.findPathBetween(graph, "vertex1", "vertex5");
System.out.println(shortest_path);
}
}

