Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graph representation using linked list & matrix

I know how to implement graph using linked list or Matrix. But i want to know when to use Linked List & when to use matrix for graph representation?

like image 489
Desire Avatar asked Dec 21 '11 08:12

Desire


People also ask

Can graph be represented as linked list?

In undirected graphs, two nodes are connected in bi-direction vertex. We can use both Array List and Linked List collections to represent the undirected graphs.

What is graph representation in data structure?

A graph can be represented using 3 data structures- adjacency matrix, adjacency list and adjacency set. An adjacency matrix can be thought of as a table with rows and columns. The row labels and column labels represent the nodes of a graph.

What is graph representation in algorithm?

In graph theory, a graph representation is a technique to store graph into the memory of computer. To represent a graph, we just need the set of vertices, and for each vertex the neighbors of the vertex (vertices which is directly connected to it by an edge).


3 Answers

V = number of vertices in graph

Points favouring Matrix:
1. You can access an edge (find out whether an edge exists between two vertices) given its end vertices in constant time whereas it takes O(degree(vertex)) time while using adjacency list.
2. Matrix is good if your graph is dense. Otherwise it wastes space because it uses O(V*V) space.

Points favouring adjacency list:
1. You need O(V) time to iterate get the neighbours of a vertex whereas it takes O(degree(Vertex)) if you use adjacency list.
2. Adjacency list does not take a lot of space.

like image 121
Divya Avatar answered Sep 30 '22 18:09

Divya


Usually, when your graph is dense. It is a good idea to use matrix , since the 'loss' of unused memory and not needed reads is neglected.
You usually also use a matrix when you want to know fast if an edge exist, or you want to preform matrix ops on the graph [such as Page Rank] (*)

A linked list is usually prefered if you are going to use all edges for each vertex, when reading it [for example: on BFS].

(*)Note that page rank behind the scenes is usually using a linked list since the graph is very sparsed, but we regard it as a "sparsed matrix"...

like image 28
amit Avatar answered Sep 30 '22 17:09

amit


There is two fundamental differences between those two implementations in terms of memory consumption and complexity.

  1. The matrix representation allow random access to elements, constant time insertion and removal of elements but (in general) it consume more space.
  2. The linked list in the other hand is more memory friendly but access to element and neighbours can take linear time.
like image 45
Ghassen Hamrouni Avatar answered Sep 30 '22 17:09

Ghassen Hamrouni