C program to implement DFS traversal using Adjacency Matrix in a given Graph


Introduction

Graph theory allows us to study and visualize relationships between objects or entities. In the current technology of computer science, graph traversal plays a crucial role in exploring and analyzing different types of data structures. One of the crucial operations performed on graphs is traversal - visiting all vertices or nodes, following specific paths. DFS traversal, based on a depth-first approach, allows us to explore the depths of a graph before backtracking and exploring other branches. In this article, we will involve in implementing DFS traversal using an adjacency matrix representation in C.

DFS traversal using Adjacency Matrix

A graph consists of two main components namely vertices or the nodes representing entities or elements, and edges that connect these vertices depicting relationships between them.

The only way to represent relations between vertices within a weighted or unweighted graph is by adjacency matrix. It typically takes the form of a square matrix where rows indicate source vertices, columns denote destination vertices, and each cell contains information about edge existence or weight between corresponding pairs.

Example

The input is given with a certain set of elements using four vertices of the graph. The input is:

1 0 0 1
0 1 1 0
0 1 1 0
1 0 0 1

And let the starting vertex for the graph be 2. The graph will start its traversal from the vertex '2'. The adjacent vertex of the vertex '2' would obviously be 1 and 3. As the starting vertex is a 2, it cannot be visited again during the traversal. Vertex 3 is visited after vertex 2, then we need to look into vertex 3 adjacency vertices which are 1 and 2. The vertex 1 and vertex 2 are already visited and the traversal stops.

Approach 1: C program to that includes DFS traversal using Adjacency Matrix as input in a given graph

The input is defined with certain numbers and using the for loop it will iterate through the adjacency matrix and returns the DFS traversal.

Algorithm

Step 1: The program starts by defining a constant `MAX` to represent the maximum number of nodes in our given graph and initializes an array called `visited` to keep track of whether a particular node has been visited during traversal.

Step 2: The 'dfs()' function takes as parameters a square adjacency matrix as `adjMatrix` representing our graph, the total number of vertices as 'vCount', and a starting vertex as `start`. This function performs recursive depth-first search traversal on the given graph.

Step 3: Within the 'dfs()' function, we mark each currently processed vertex as "visited" using indexing in the Boolean-based 'visited[]' array and print its value accordingly.

Step 4: The loop inside 'dfs()' iterates through all unvisited neighbors of our current node recursively until there is no possibility to get the vertices connected to it.

Step 5: In main(), we read inputs from users such as the number of vertices as 'vCount' and their corresponding connections into an adjacency matrix using nested loops.

Step 6: We then prompt users to enter their desired starting vertex before initializing every element of our 'visited[]' array to zero (as none of the nodes have been visited yet).

Step 7: Finally, the program calls the 'dfs()' function with appropriate arguments to initiate depth-first search traversal, printing out the DFS traversal path.

Example

//Including the required header files
#include<stdio.h>
#define MAX 100

int visited[MAX];
//dfs function is defined with three arguments
void dfs(int adjMatrix[][MAX], int vCount, int start) {
   visited[start] = 1;
   printf("%d ", start);

   for(int i=0; i<vCount; i++) {
      if(adjMatrix[start][i] && !visited[i]) {
         dfs(adjMatrix,vCount,i);
      }
   }
}
//main function is used to implement the above functions
int main() {
   int adjMatrix[MAX][MAX];
   int vCount;

   // Assigning the variable with value of 4
   vCount = 4;

   // Assigning the adjacency matrix directly same the example given above
   adjMatrix[0][0] = 1;
   adjMatrix[0][1] = 0;
   adjMatrix[0][2] = 0;
   adjMatrix[0][3] = 1;
   adjMatrix[1][0] = 0;
   adjMatrix[1][1] = 1;
   adjMatrix[1][2] = 1;
   adjMatrix[1][3] = 0;
   adjMatrix[2][0] = 0;
   adjMatrix[2][1] = 1;
   adjMatrix[2][2] = 1;
   adjMatrix[2][3] = 0;
   adjMatrix[3][0] = 1;
   adjMatrix[3][1] = 0;
   adjMatrix[3][2] = 0;
   adjMatrix[3][3] = 1;
//Declaring the start variable as integer data type and later assigned with a value of 2
   int start;
   
   // Assigning the starting vertex directly
   start = 2;
   
   for(int i = 0; i < MAX; ++i) {
      visited[i] = 0;
   }

   printf("\nDFS Traversal: ");
   dfs(adjMatrix, vCount, start);
   

   return 0;
}

Output

DFS Traversal: 2 1

Conclusion

By using adjacency matrices as representations of graphs, we can efficiently perform DFS on large or complex data sets. In this article, we detailed the explanation and presented a C program that implements Depth-First Search traversal using an adjacency matrix-based representation.Depth-First Search is a powerful algorithm for exploring and analyzing graph structures.

Updated on: 09-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements