I'm implementing some algorithms to teach myself about graphs and how to work with them. What would you recommend is the best way to do that in Java? I was thinking something like this:
public class Vertex { private ArrayList<Vertex> outnodes; //Adjacency list. if I wanted to support edge weight, this would be a hash map. //methods to manipulate outnodes } public class Graph { private ArrayList<Vertex> nodes; //algorithms on graphs }
But I basically just made this up. Is there a better way?
Also, I want it to be able to support variations on vanilla graphs like digraphs, weighted edges, multigraphs, etc.
In Java, plotting of graph is done by using several topics of core Java. For plotting, we use swing, awt, and awt. geom. We use Swing package to use Jlabel, JButtons, and JPanel in our program.
A graph can be represented using 3 data structures- adjacency matrix, adjacency list and adjacency set. An adjacency matrix can be thought of as a table with rows and columns. The row labels and column labels represent the nodes of a graph.
The main two approaches to representing graphs in code are adjacency matrices and adjacency lists.
Java Universal Network/Graph (JUNG) is a Java framework that provides extensible language for modeling, analysis and visualization of any data that can be represented as a graph.
Each node is named uniquely and knows who it is connected to. The List of connections allows for a Node to be connected to an arbitrary number of other nodes.
public class Node { public String name; public List<Edge> connections; }
Each connection is directed, has a start and an end, and is weighted.
public class Edge { public Node start; public Node end; public double weight; }
A graph is just your collection of nodes. Instead of List<Node>
consider Map<String, Node>
for fast lookup by name.
public class Graph { List<Node> nodes; }
If you need weighted edges and multigraphs, you might want to add another class Edge.
I would also recommend using generics to allow specifying which sub-class of Vertex and Edge are currently used. For example:
public class Graph<V extends Vertex> { List<V> vertices; ... }
When it comes to implementing graph algorithms, you could also define interfaces for your graph classes on which the algorithms can operate, so that you can play around with different implementations of the actual graph representation. For example, simple graphs that are well-connected might be better implemented by an adjacency matrix, sparser graphs might be represented by adjacency lists - it all depends...
BTW Building such structures efficiently can be quite challenging, so maybe you could give us some more details on what kind of job you would want to use them for? For more complex tasks I would suggest you have a look at the various Java graph libraries, to get some inspiration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With