VOOZH about

URL: https://www.geeksforgeeks.org/c/c-program-to-implement-adjacency-matrix-of-a-given-graph/

⇱ C program to implement Adjacency Matrix of a given Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C program to implement Adjacency Matrix of a given Graph

Last Updated : 12 Jul, 2025

Given a undirected Graph of N vertices 1 to N and M edges in form of 2D array arr[][] whose every row consists of two numbers X and Y which denotes that there is a edge between X and Y, the task is to write C program to create Adjacency Matrix of the given Graph. Examples:

Input: N = 5, M = 4, arr[][] = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 1, 5 } } Output: 0 1 0 0 1 1 0 1 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 1 0 Input: N = 3, M = 4, arr[][] = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 2, 2 } } Output: 0 1 1 1 1 1 1 1 0

Approach: The idea is to use a square Matrix of size NxN to create Adjacency Matrix. Below are the steps:

  1. Create a 2D array(say Adj[N+1][N+1]) of size NxN and initialise all value of this matrix to zero.
  2. For each edge in arr[][](say X and Y), Update value at Adj[X][Y] and Adj[Y][X] to 1, denotes that there is a edge between X and Y.
  3. Display the Adjacency Matrix after the above operation for all the pairs in arr[][].

Below is the implementation of the above approach: 

Output:
0 1 0 0 1 
1 0 1 0 0 
0 1 0 0 0 
0 0 0 0 1 
1 0 0 1 0

Time Complexity: O(N^2), where N is the number of vertices in a graph.

Space Complexity: O(N^2), where N is the number of vertices.

Comment
Article Tags:
Article Tags: