Given an adjacency list representation of a **Graph**, the task is to convert the given **Adjacency List** to **Adjacency Matrix** representation.

**Examples:**

_ adjList[] = {{0 –> 1 –> 3}, {1 –> 2}, {2 –> 3}} _Input:

Output:

0 1 0 1

0 0 1 0

0 0 0 1

0 0 0 0

_ adjList[] = {{0 –> 1 –> 4}, {1 –> 0 –> 2 –> 3 –> 4}, {2 –> 1 –> 3}, {3 –> 1 –> 2 –> 4}, {4 –> 0 –> 1 –> 3}} _Input:

Output:

0 1 0 0 1

1 0 1 1 1

0 1 0 1 0

0 1 1 0 1

_1 1 0 1 0 _

**Recommended: Please try your approach on {IDE} first, before moving on to the solution.**

**Adjacency List:** An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array[]. An entry array[i] represents the list of vertices adjacent to the ith Vertex.

**Adjacency Matrix:** Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j.

Follow the steps below to convert an adjacency list to an adjacency matrix:

- Initialize a matrix with
**0**s. - Iterate over the vertices in the adjacency list
- For every
**jth**vertex in the adjacency list, traverse its edges. - For each vertex
**i**with which the**jth**vertex has an edge, set mat[i][j] = 1.

#data structures #graph #graph traversals #graph-basics #data analysis

58.80 GEEK