简体   繁体   中英

When representing a sparse graph with an adjacency matrix, why use linked list as structure to contain edges?

When representing graphs in memory in a language like Java, either an adjacency matrix is used (for dense graphs) or an adjacency list for sparse graphs.

So say we represent the latter like

Map<Integer, LinkedList<Integer>> graph;

The integer key represents the vertex and LinkedList contains all the other vertexes it points to.

Why use a LinkedList to represent the edges? Couldn't an int[] or ArrayList work just as fine, or is there a reason why you want to represent the edges in a way that maintains the ordering such as

2 -> 4 -> 1 -> 5

Either an int[] or ArrayList could also work.

I wouldn't recommend an int[] right off the bat though, as you'll need to cater for resizing in case you don't know all the sizes from the start, essentially simulating the ArrayList functionality, but it might make sense if memory is an issue.

A LinkedList might be slightly preferable since you'd need to either make the array / ArrayList large enough to handle the maximum number of possible edges, or resize it as you go, where-as you don't have this problem with a LinkedList , but then again, creating the graph probably isn't the most resource-intensive task for most applications.

Bottom line - it's most likely going to make a negligible difference for most applications - just pick whichever one you feel most comfortable with (unless of course you need to do access-by-index a lot, or something which one of the two performs a lot better than the other).

Algorithms 4th Edition by Sedgewick and Wayne proposes the following desired performance characteristics for a graph implementation that is useful for most graph-processing applications:

  1. Space usage proportional to V + E
  2. Constant time to add an edge
  3. Time proportional to the degree of v to iterate through vertices adjacent to v (constant time per adjacent vertex processed)

Using a linked list to represent the vertices adjacent to each vertex has all these characteristics. Using an array instead of a linked list would result in either (1) or (2) not being achieved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM