Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
Add and Remove vertex in Adjacency Matrix representation of Graph
Next article icon

Graph Representation using Adjacency Matrix in C

Last Updated : 07 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A graph is a data structure having a set of vertices and a collection of edges that each connect a pair of vertices. There are several ways to represent a graph in computer memory, and one of them is using an adjacency matrix. An adjacency matrix is a 2D array with one row per vertex and one column per edge. In this article, we will discuss graph representation using an adjacency matrix in C programming language.

Adjacency Matrix Representation of Graph in C

The adjacency matrix is a way of representing a graph where rows represent vertices and columns represent edges. The elements of the matrix indicate the relationship between vertices and edges. The rows of the matrix represent the vertices and the columns of the matrix represent the edges of the graph.

  • In C, we can create a 2D array of size V * V where V is the number of vertices.
  • Initially, set all the elements of the matrix to 0.
  • For each edge in the graph, if the graph is unweighted, set the corresponding element in the matrix to 1.
  • If the graph is weighted, set the corresponding element in the matrix to the weight of the edge.
  • If the graph is undirected, the matrix will be symmetric, meaning if there is an edge from node i to node j, there will also be an edge from node j to node i, so both matrix[i][j] and matrix[j][i] should be set.
undirected-weighted-graph


Adjacency Matrix for the Above Undirected Graph

Following is the incidence matrix to represent the above-undirected graph:

Vertex NameABCDEFG
A0140000
B1002300
C4000067
D0200500
E0305000
F0060000
G0070000

In the above incidence matrix:

  • Each column corresponds to an edge.
  • A is connected to B (weight 1) and C (weight 4)
  • B is connected to A (weight 1), D (weight 2), and E (weight 3)
  • C is connected to A (weight 4), F (weight 6), and G (weight 7)
  • D is connected to B (weight 2) and E (weight 5)
  • E is connected to B (weight 3) and D (weight 5)
  • F is connected to C (weight 6)
  • G is connected to C (weight 7)
  • In each column, there are two 1s indicating the vertices that are connected by the edge.

C Program to Represent Graph Using Adjacency Matrix

The following program represents how we can represent a graph using adjacency matrix in C:

C
// C Program to represent the graph using ajacency matrix #include <stdio.h> #include <stdlib.h>  // Structure to represent a graph typedef struct {     int vertices;     int** adjMatrix; } Graph;  // Function to create a graph Graph* createGraph(int vertices) {     Graph* graph = (Graph*)malloc(sizeof(Graph));     graph->vertices = vertices;      // Allocate memory for the adjacency matrix     graph->adjMatrix         = (int**)malloc(vertices * sizeof(int*));     for (int i = 0; i < vertices; i++) {         graph->adjMatrix[i]             = (int*)calloc(vertices, sizeof(int));     }      return graph; }  // Function to add an edge to the graph (undirected) void addEdge(Graph* graph, int src, int dest) {     if (src >= graph->vertices || dest >= graph->vertices) {         printf("Invalid vertices!\n");         return;     }     graph->adjMatrix[src][dest] = 1;     // for a directed graph, set weight     graph->adjMatrix[dest][src] = 1; }  // Function to display the adjacency matrix void displayAdjMatrix(Graph* graph) {     printf("Adjacency Matrix:\n");     for (int i = 0; i < graph->vertices; i++) {         for (int j = 0; j < graph->vertices; j++) {             printf("%d ", graph->adjMatrix[i][j]);         }         printf("\n");     } }  // Function to free the allocated memory for the graph void freeGraph(Graph* graph) {     for (int i = 0; i < graph->vertices; i++) {         free(graph->adjMatrix[i]);     }     free(graph->adjMatrix);     free(graph); }  int main() {     int vertices = 5;      // Create a graph     Graph* graph = createGraph(vertices);      // Add edges to the graph     addEdge(graph, 0, 1);     addEdge(graph, 0, 4);     addEdge(graph, 1, 2);     addEdge(graph, 1, 3);     addEdge(graph, 1, 4);     addEdge(graph, 2, 3);     addEdge(graph, 3, 4);      // Display the adjacency matrix     displayAdjMatrix(graph);      // Free the allocated memory     freeGraph(graph);      return 0; } 

Output
Incidence Matrix: 1 1 1 0 0  1 0 0 1 0  0 1 0 0 1  0 0 1 1 1  

Time Complexity : O(V x E), where V represents the number of vertices in the graph and E represents the edges.
Auxiliary Space: O(V x E)

Related Articles

You can also go through the following articles to improve your understanding about the graph data structure:

  • C++ Program to Implement Adjacency Matrix
  • Graph and its representations
  • Adjacency matrix meaning and definition in DSA



Next Article
Add and Remove vertex in Adjacency Matrix representation of Graph

R

rohitpant4532
Improve
Article Tags :
  • C Language
  • C-DSA

Similar Reads

  • Graph Representation using Incidence Matrix in C++
    A graph is a non-linear data structure that is represented as a collection of vertices and edges that connect pairs of vertices. One way to represent a graph in computer memory is using an incidence matrix. An incidence matrix is a 2D array where rows represent edges and columns represent vertices.
    6 min read
  • Adjacency Matrix Representation
    Adjacency Matrix is a square matrix used to represent a finite graph. The elements of the matrix indicate whether pairs of vertices are adjacent or not in the graph. An adjacency matrix is a simple and straightforward way to represent graphs and is particularly useful for dense graphs. Table of Cont
    9 min read
  • Add and Remove vertex in Adjacency Matrix representation of Graph
    A graph is a presentation of a set of entities where some pairs of entities are linked by a connection. Interconnected entities are represented by points referred to as vertices, and the connections between the vertices are termed as edges. Formally, a graph is a pair of sets (V, E), where V is a co
    15+ min read
  • Add and Remove Edge in Adjacency Matrix representation of a Graph
    Prerequisites: Graph and its representationsGiven an adjacency matrix g[][] of a graph consisting of N vertices, the task is to modify the matrix after insertion of all edges[] and removal of edge between vertices (X, Y). In an adjacency matrix, if an edge exists between vertices i and j of the grap
    13 min read
  • Adjacency List Representation
    An adjacency list is a data structure used to represent a graph where each node in the graph stores a list of its neighboring vertices. Table of Content 1. Adjacency List for Directed graph:2. Adjacency List for Undirected graph:3. Adjacency List for Directed and Weighted graph:4. Adjacency List for
    14 min read
  • Add and Remove vertex in Adjacency List representation of Graph
    Prerequisites: Linked List, Graph Data Structure In this article, adding and removing a vertex is discussed in a given adjacency list representation. Let the Directed Graph be: The graph can be represented in the Adjacency List representation as: It is a Linked List representation where the head of
    10 min read
  • Add and Remove Edge in Adjacency List representation of a Graph
    Prerequisites: Graph and Its RepresentationIn this article, adding and removing edge is discussed in a given adjacency list representation. A vector has been used to implement the graph using adjacency list representation. It is used to store the adjacency lists of all the vertices. The vertex numbe
    8 min read
  • Adjacency Matrix in Python
    Given the edges of a graph as a list of tuples, construct an adjacency matrix to represent the graph in Python. Examples: Input:V = 3 (Number of vertices)edges = [(0, 1), (1, 2), (2, 0)] Output: [ [0, 1, 1], [1, 0, 1], [1, 1, 0]] Input:V = 4 (Number of vertices)edges = [(0, 1), (1, 2), (1, 3), (2, 3
    2 min read
  • Graph Adjacency Matrix in Java
    A graph is a type of data structure used to represent the relationship between the entities. In this article, we will learn to represent a graph in the form of Adjacency Matrix. Graph Adjacency MatrixThe Adjacency matrix is the way to represent the graphs using the 2D array. It is the fundamental da
    6 min read
  • Adjacency Matrix of Directed Graph
    Adjacency Matrix of a Directed Graph is a square matrix that represents the graph in a matrix form. In a directed graph, the edges have a direction associated with them, meaning the adjacency matrix will not necessarily be symmetric. In a directed graph, the edges have a direction associated with th
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences