Perform a DFS traversal over a graph represented using an adjacency matrix.


Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<stdlib.h>
typedef struct {
	int V;
	int E;
	int **Adj; // since we need 2 dimensional matrix
} Graph;

Graph* adjacencyMatrix() {
	int i, u, v;
	Graph* G=(Graph*) malloc(sizeof(Graph));
	printf("Enter the number of Vertices: ");
	scanf("%d", &G->V);
	printf("Enter the number of Edges: ");
	scanf("%d", &G->E);
	G->Adj = (int **)malloc(G->V * sizeof(int*));
	for (u = 0; u < G->V; u++)
		G->Adj[u] = (int *)malloc(G->V * sizeof(int));

	for (u = 0; u<G->V; u++)
		for (v = 0; v<G->V; v++)
			G->Adj[u][v] = 0;
	for (i = 0; i < G->E; i++) {
		printf("Enter the edge: ");
		scanf("%d %d", &u,&v);
		// for undirected graph, set both
		G->Adj[u][v] = 1;
		G->Adj[v][u] = 1;
	}
	return G;
}

void DFSTraversal(Graph* G, int index, int Visited[]) {
	int v;
 	printf("%d ",index);
	for (v = 0; v < G->V; v++) {
		if (!Visited[v] && G->Adj[index][v])
		{
		    Visited[v]=1;
			DFSTraversal(G, v, Visited);
		 }
	}
}

void DFS(Graph *G) {
	int i;
	int *Visited;
	Visited = (int *)malloc(G->V * sizeof(int));

	for (i = 0; i < G->V; i++)
		Visited[i] = 0;

	// this loop is required if the graph has more than one component
	for (i = 0; i < G ->V; i++)
		if (!Visited[i])
		{
			Visited[i] = 1;
			DFSTraversal(G, i, Visited);
		}
}


void test() {
	int u, v;
	Graph *G = adjacencyMatrix();
	DFS(G);
}

int main()
{
	test();
	return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
N-ary tree