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!
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.