📅  最后修改于: 2023-12-03 15:07:54.118000             🧑  作者: Mango
在软件开发中,图是一种经常使用的数据结构。不同的应用场景需要不同类型的图。有的图是有向的,有的是无向的;有的图是带权重的,有的则没有。
Java编程语言为开发者提供了丰富的数据结构和算法,其中包括了一些图的实现,比如JGraphT和GraphStream。
JGraphT是一个开源的Java图形库,支持无向图、有向图和混合图的创建和处理。它也提供了多种不同的图算法,例如最短路径、最小生成树以及最大流等。
import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
public class Main {
public static void main(String[] args) {
Graph<Character, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class);
graph.addVertex('A');
graph.addVertex('B');
graph.addVertex('C');
graph.addVertex('D');
graph.addEdge('A', 'B');
graph.addEdge('B', 'C');
graph.addEdge('C', 'D');
graph.addEdge('D', 'A');
graph.addEdge('A', 'C');
System.out.println(graph.toString());
}
}
import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DirectedMultigraph;
public class Main {
public static void main(String[] args) {
Graph<Character, DefaultEdge> graph = new DirectedMultigraph<>(DefaultEdge.class);
graph.addVertex('A');
graph.addVertex('B');
graph.addVertex('C');
graph.addVertex('D');
graph.addEdge('A', 'B');
graph.addEdge('B', 'C');
graph.addEdge('C', 'D');
graph.addEdge('D', 'A');
graph.addEdge('A', 'C');
System.out.println(graph.toString());
}
}
GraphStream也是一个开源的Java图形库,支持多种类型的图形。它提供的算法包括图形布局和图形分析等。其中,图形布局是指如何将节点组织成一个可视化的图形。
import org.graphstream.graph.Graph;
import org.graphstream.graph.Node;
import org.graphstream.graph.implementations.SingleGraph;
public class Main {
public static void main(String[] args) {
Graph graph = new SingleGraph("Graph");
graph.setAutoCreate(true);
graph.addEdge("AB", "A", "B");
graph.addEdge("BC", "B", "C");
graph.addEdge("CD", "C", "D");
graph.addEdge("DA", "D", "A");
graph.addEdge("AC", "A", "C");
for (Node n : graph) {
n.addAttribute("ui.label", n.getId());
}
graph.display();
}
}
import org.graphstream.graph.Graph;
import org.graphstream.graph.Node;
import org.graphstream.graph.implementations.MultiGraph;
public class Main {
public static void main(String[] args) {
Graph graph = new MultiGraph("Graph");
graph.setAutoCreate(true);
graph.addEdge("AB", "A", "B");
graph.addEdge("BC", "B", "C");
graph.addEdge("CD", "C", "D");
graph.addEdge("DA", "D", "A");
graph.addEdge("AC", "A", "C");
graph.addEdge("CB", "C", "B");
for (Node n : graph) {
n.addAttribute("ui.label", n.getId());
}
graph.display();
}
}
以上是JGraphT和GraphStream创建图的基本用法,开发者可以根据不同的需求来选择合适的库。