Representation of Graph using adjacency matrix and adjacency list in C
Graph is a non-linear data structure. It can be represented by adjacency matrix or adjacency list.
Let us discuss the methods in detail.
This blog post deals with the first method Adjacency matrix.
Adjacency matrix:
It is a two-dimensional
matrix.it deals with the edges present between nodes.
If the edges found,
it assigns the weight as 1. Otherwise, it values it as 0.
Code implementation:
- This code includes the built-in header file.
- It defines the vertices as 4. A function ‘Display_Matrix()’ is used to represent the graph.
- ‘main()’ function initialises the graph. It assigns the value for matrix.
- Finally,it calls the ‘Display_Matrix’ function to display the output.
Code:
#include <stdio.h>
#define V 4 //
Declare the number of vertices
void Display_Matrix(int graph[V][V]) {
for (int i = 0; i
< V; i++) {
for (int j =
0; j < V; j++) {
printf("%d ", graph[i][j]);
}
printf("\n");
}
}
int main() {
int graph[V][V] =
{0}; // initialize with 0
// let us add
the edges (like undirected graph)
graph[0][1] = 1;
graph[1][0] = 1;
graph[0][3] = 1;
graph[3][0] = 1;
graph[1][2] = 1;
graph[2][1] = 1;
graph[2][3] = 1;
graph[3][2] = 1;
printf("Adjacency
Matrix:\n");
Display_Matrix(graph);
return 0;
}
Output:
Adjacency Matrix:
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
Hope, this implementation of adjacency matrix is useful to
you. If
your graph has lots of edges(dense), use adjacency matrix. Keep
Coding!!!!!
Comments
Post a Comment