Home Data Structures Representation of a Graph using Adjacency List and Adjacency Matrix

Representation of a Graph using Adjacency List and Adjacency Matrix

In computer science graph is a data structure consisting of vertices and edges. It is usually represented as G(V, E) where V is a set of vertices and E is the set of all the edges.

We have two ways of representing a graph:

  1. Adjacency List Representation (for a sparse graph)
  2. Adjacency Matrix Representation (for a dense graph)

Adjacency List: In adjacency list representation we have a list of sizes equals to total no. of vertices. Each entry of the list contains another list, which is the set of all the vertices adjacent to the current vertex.

Note 1)For an undirected graph(unlike here) we will add an edge from both, vertex u to vertex v and from vertex v to vertex u.
2) For a weighted graph, we will add and extra weight parameter to the adjacency list representation.

Image result for adjacency list

CPP code for Adjacency List representation:


Adjacency Matrix: In adjacency matrix representation we have an array of size VxV and if a vertex(u) is connected to any other vertex(v) then we set the corresponding entry of the array (a[u][v]) as 1.
Note:1)For a weighted graph, we will represent a[u][v] = w(instead of 1), where w is the weight of the corresponding edge from vertex u to v.
2) If it’s an undirected graph then we will put a[u][v] = a[v][u] = 1 (or w is it’s a weighted graph and w is the edge weight).

Here the adjacency matrix formed for the above graph is:

    1   2   3   4   5
 0   1   1   1   0
2   0   0   1   0   0
3   0   0   0   1   0
4   0   0   0   1  0
5   0   1   0   0   0

CPP code for Adjacency Matrix representation:

Output for both the programs:
vetex 1 is connected to: 2 3 4
vetex 2 is connected to: 3
vetex 3 is connected to: 4
vetex 4 is connected to: 4
vetex 5 is connected to: 2

Subscribe to our weekly newsletter

Join our community of 1000+ developers and stay updated with the fast moving world of computer science

We promise, we won't spam
Even we hate spam as much as you hate them


Please enter your comment!
Please enter your name here