Write a Modular C Programming code to implement DFS traversal using Adjacency Matrix in a given Graph DSA
Example:
Input: V = 7, E = 7
Connections: 0-1, 0-2, 1-3, 1-4, 1-5, 1-6, 6-2
See the diagram for connections:
Output : 0 1 3 4 5 6 2
Explanation: The traversal starts from 0 and follows the following path 0-1, 1-3, 1-4, 1-5, 1-6, 6-2.
Input: V = 1, E = 0
Output: 0
Explanation: There is no other vertex than 0 itself.
CODE:
#include<stdio.h> #define V 9 // Recursive function to perform DFS void DFS(int graph[V][V], int visited[V], int v) { visited[v] = 1; // Mark current vertex as visited printf("%d ", v); // Visit all adjacent vertices of current vertex for (int i = 0; i < V; i++) { if (graph[v][i] && !visited[i]) { DFS(graph, visited, i); } } } int main() { // Example adjacency matrix int graph[V][V] = { {0, 1, 0, 0, 1, 1, 0, 0, 0}, {1, 0, 1, 0, 0, 0, 1, 0, 0}, {0, 1, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 1, 0, 0, 1}, {1, 0, 0, 0, 1, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0, 1}, {0, 0, 0, 1, 1, 0, 0, 1, 0} }; int visited[V] = { 0 }; // Initialize all vertices as unvisited printf("DFS travel from vertex 0: "); DFS(graph, visited, 0); // Start DFS from vertex 0 return 0; }
OUTPUT
DFS travel from vertex 0: 0 1 2 3 8 4 5 7 6 Process returned 0 (0x0) execution time : 0.032 s Press any key to continue.
Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, Stacks, Queues, Binary Trees, MISC, Solved model question papers & Hacker Rank all solutions on the below page:
Top 100+ C Programming codes – KLE Technological University