I can't use any external libraries, so I'm trying to think of some ways to build the data structure myself. I was thinking maybe something like this:
public class Node{
Set<Edge> adjacent;
int value;
}
public class Edge{
Node target;
int weight;
}
But I'm guessing there's probably a better way to do it.
My eventual use for this graph is to run the Bellman Ford algorithm on it, but I obviously need a functioning graph first!
A weighted graph refers to one where weights are assigned to each edge. Weighted graphs can be represented in two ways: Directed graphs where the edges have arrows that show path direction. Undirected graphs where edges are bi-directional and have no arrows.
There are three ways to store a graph in memory: Nodes as objects and edges as pointers. A matrix containing all edge weights between numbered node x and node y. A list of edges between numbered nodes.
The answer depends a lot on the algorithms that you are planning to apply to your graphs.
There are two common ways to represent a graph - an adjacency list and an adjacency matrix. In your case, and adjacency matrix is a square array of integers representing weights. Your representation uses an adjacency list.
There are algorithms that work better on adjacency matrixes (e.g. Floyd-Warshall algorithm). Other algorithms work better on adjacency lists (e.g. Dijkstra's algorithm). If your graph is sparse, using adjacency matrix may be prohibitive.
As usual, you can represent graphs as Adjacency Lists or Adjacency Matrices. The choice really depends on the details of your problem.
Using an Adjacency Matrix, you could simply have a matrix of integers, representing the weight.
If you decide to have an Adjacency List, you could simply store a list of list of integers (assuming the nodes of your graph are identified by an integer value), similar to what you've done.
You can use a node as in an unweighted graph, holding a list of nodes to which it is connected,and additionally add the weights associated with the connections as:
public class Node{
int value;
HashMap<Node,Integer> adjacency;
}
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