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:

- Adjacency List Representation (for a sparse graph)
- 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.

**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**

**1 ** 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