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?
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.
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.
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).
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.
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"...
There is two fundamental differences between those two implementations in terms of memory consumption and complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With