Adjacency Matrix Graph: In this post we will study about the implementation of adjacency matrix graph.
The given code have 4 major functions:
- One is creating the edge
- One is removing the edge
- One is checking the edge
- Other is printing the edge
Adjacency Matrix Graph Code In C
#include<stdio.h>
#define V 5
void def(int arr[][V])
{
int i,j;
for(i = 0; i < V; i++)
for(j = 0; j < V; j++)
arr[i][j] = 0;
}
void addEdge(int arr[][V],int a, int b)
{
arr[a][b] = 1;
}
void print(int arr[][V])
{
int i, j;
for(i = 0; i < V; i++)
{
for(j = 0; j < V; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int hasEdge(int arr[][V], int a, int b)
{
if(arr[a][b] == 1)
return 1;
return 0;
}
void removeEdge(int arr[][V], int a, int b)
{
arr[a][b] = 0;
}
int main()
{
int adj[V][V];
def(adj);
addEdge(adj,0,1);
addEdge(adj,1,2);
addEdge(adj,2,1);
addEdge(adj,3,3);
addEdge(adj,4,3);
print(adj);
printf("Removing Edge(0, 1)\n");
removeEdge(adj,0,1);
print(adj);
printf("(0,1) has Edge?\n");
if(hasEdge(adj,0, 1) == 1)
printf("Edge Found\n");
else
printf("Edge Not Found\n");
printf("(0,2) has Edge?\n");
return 0;
}
In the above code, we are doing following things:
- First we are creating a matrix and initializing 0 values to each rows and columns.
- After this if we want to add an edge between any two vertices then we will make that equal to 1.
- If we want to remove then we will again update the value to 0.
- So we are using two dimensional array concept to implement adjacency matrix graph.