I am trying to figure out the best way to implement a Weighted Directed Graph in Java so to I can keep the running time on Bellman-Ford to |V|*|E|. Essentially my question is on how to represent the edges in the graph.
I have seen the use of an adjacency matrix, but I cannot seem to figure out how to use an adjacency matrix while at the same time keeping the running time below O(V^2). The reason I get V^2 as the running time is because Bellman-Ford requires that we loop through all edges, but it order to get a list of the edges I would need to loop through the entire matrix to get all edges. Is there anyway to get the list of edges faster than O(V^2) time with using an adjacency matrix?
Or do I need to use an adjacency list?
You can easily implement a class for Adjacency List. Following is the class which I use as an Adjacency List quite often which is easy to understand also. It maps an
integer
to alinked list
.Before you complain that I need to implement a weighted graph, think about mapping a
HashMap
to anInteger
. You can change the functions accordingly by replacinglinked list
withhash map
. This saves you from O(n^2) time complexity.