Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three ways to store a graph in memory, advantages and disadvantages

Tags:

graph

There are three ways to store a graph in memory:

  1. Nodes as objects and edges as pointers
  2. A matrix containing all edge weights between numbered node x and node y
  3. A list of edges between numbered nodes

I know how to write all three, but I'm not sure I've thought of all of the advantages and disadvantages of each.

What are the advantages and disadvantages of each of these ways of storing a graph in memory?

like image 762
Dean J Avatar asked Jul 20 '10 04:07

Dean J


People also ask

What are the advantages and disadvantages of adjacency list?

Advantages and Disadvantages Adjacency matrices are helpful when we need to quickly check if two nodes have a direct edge or not. However, the main disadvantage is its large memory complexity. The adjacency matrix is most helpful in cases where the graph doesn't contain a large number of nodes.

What are the two ways of representing graph in memory?

A graph is a data structure that consist a sets of vertices (called nodes) and edges. There are two ways to store Graphs into the computer's memory: Sequential representation (or, Adjacency matrix representation) Linked list representation (or, Adjacency list representation)

Which method is used to store a graph?

Vectors. It's the most common method for saving graph. For each vertex keep a vector of it's edges, now for each edge just save it in related vectors.


1 Answers

One way to analyze these is in terms of memory and time complexity (which depends on how you want to access the graph).

Storing nodes as objects with pointers to one another

  • The memory complexity for this approach is O(n) because you have as many objects as you have nodes. The number of pointers (to nodes) required is up to O(n^2) as each node object may contain pointers for up to n nodes.
  • The time complexity for this data structure is O(n) for accessing any given node.

Storing a matrix of edge weights

  • This would be a memory complexity of O(n^2) for the matrix.
  • The advantage with this data structure is that the time complexity to access any given node is O(1).

Depending on what algorithm you run on the graph and how many nodes there are, you'll have to choose a suitable representation.

like image 158
f64 rainbow Avatar answered Sep 21 '22 00:09

f64 rainbow