C Adjacency Matrix 🎯

beginner
12 min

C Adjacency Matrix 🎯

Welcome to a comprehensive guide on understanding and implementing C Adjacency Matrix, a powerful data structure used for representing the relationship between nodes (vertices) in a graph. This guide is designed for both beginners and intermediate learners.

What is a Graph? 📝

Before diving into Adjacency Matrix, let's first understand what a graph is. A graph is a collection of nodes (vertices) and edges that connect them. In a graph, nodes can represent entities like cities, people, or objects, while edges represent relationships between these entities.

Introduction to Adjacency Matrix 💡

Adjacency Matrix is a type of matrix (a two-dimensional array) used to represent a finite graph. Each entry in the matrix indicates the presence or absence of an edge between two vertices.

Creating an Adjacency Matrix 🎯

Let's consider a simple graph with 5 vertices: A, B, C, D, and E.

Here's how you can create an Adjacency Matrix for this graph:

c
#include <stdio.h> #define MAX_VERTICES 5 void createAdjacencyMatrix(int graph[MAX_VERTICES][MAX_VERTICES]) { int i, j; // Initialize all entries as 0 (no edge) for (i = 0; i < MAX_VERTICES; i++) { for (j = 0; j < MAX_VERTICES; j++) { graph[i][j] = 0; } } // Add edges graph[0][1] = 1; graph[0][4] = 1; graph[1][0] = 1; graph[1][3] = 1; graph[1][4] = 1; graph[2][3] = 1; graph[3][1] = 1; graph[3][2] = 1; graph[4][0] = 1; graph[4][1] = 1; graph[4][2] = 1; graph[4][3] = 1; graph[4][4] = 1; } void printAdjacencyMatrix(int graph[MAX_VERTICES][MAX_VERTICES]) { int i, j; printf("Adjacency Matrix:\n"); for (i = 0; i < MAX_VERTICES; i++) { for (j = 0; j < MAX_VERTICES; j++) { printf("%d ", graph[i][j]); } printf("\n"); } } int main() { int graph[MAX_VERTICES][MAX_VERTICES]; createAdjacencyMatrix(graph); printAdjacencyMatrix(graph); return 0; }

In this code, we first create an empty Adjacency Matrix and then add edges between the vertices. Finally, we print the Adjacency Matrix to verify its structure.

Traversing a Graph using Adjacency Matrix 🎯

Adjacency Matrix provides a straightforward way to traverse a graph. However, it's important to note that it's not designed for traversing purposes. Instead, it's used to represent the graph structure itself. For traversing, other data structures like Depth-First Search (DFS) or Breadth-First Search (BFS) are better suited.

Quiz 📝

Quick Quiz
Question 1 of 1

Which of the following is NOT a correct usage of the Adjacency Matrix data structure?