Java uses JGraphT to add nodes and edges to the graph, specifying the attributes of the nodes and the weights of the edges
Maven coordinates of dependent class libraries:
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-core</artifactId>
<version>1.5.1</version>
</dependency>
A brief introduction to this library:
JGraphT is a Java class library used for representing, modeling, and manipulating diagrams. It provides a rich set of graph data structures (such as directed graphs, undirected graphs, weighted graphs, etc.), as well as related algorithms and operations.
The complete Java code for the sample is as follows:
import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleDirectedGraph;
public class GraphExample {
public static void main(String[] args) {
//Create a directed graph
Graph<String, DefaultEdge> graph = new SimpleDirectedGraph<>(DefaultEdge.class);
//Add Node
String node1 = "A";
String node2 = "B";
String node3 = "C";
graph.addVertex(node1);
graph.addVertex(node2);
graph.addVertex(node3);
//Add edges and assign weights
DefaultEdge edge1 = graph.addEdge(node1, node2);
graph.setEdgeWeight(edge1, 1.0);
DefaultEdge edge2 = graph.addEdge(node2, node3);
graph.setEdgeWeight(edge2, 2.0);
DefaultEdge edge3 = graph.addEdge(node1, node3);
graph.setEdgeWeight(edge3, 3.0);
//Output the information of the graph
System. out. println ("Node in graph:");
for (String vertex : graph.vertexSet()) {
System.out.println(vertex);
}
System. out. println ("Edges and their weights in the graph:");
for (DefaultEdge edge : graph.edgeSet()) {
String sourceVertex = graph.getEdgeSource(edge);
String targetVertex = graph.getEdgeTarget(edge);
double weight = graph.getEdgeWeight(edge);
System.out.println(sourceVertex + " -> " + targetVertex + ", weight: " + weight);
}
}
}
Summary: This article introduces the method of using JGraphT to add nodes and edges to a graph, and specify the attributes of nodes and the weights of edges. Through a simple example code, it demonstrates how to use JGraphT to create a directed graph, add nodes and edges, and output graph information. JGraphT is a powerful Java class library for graph processing, which can meet various graph related requirements, such as graph modeling, Analysis of algorithms, etc.