Perform a recursive DFS traversal over a graph represented using an adjacency list.


Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<stdlib.h>
 
typedef struct node {
	int vertexNumber;
	struct node * next;
} node;
typedef struct {
	int V;
	int E;
	node** Adj;  //array of linked list
} Graph;

Graph* adjacencyList() {
	int i, x, y;
	node * temp, *temp2;
	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 = (node **)malloc(G->V * sizeof(node));
	for (i = 0; i < G->V; i++) {
		G->Adj[i] = (node *)malloc(G->V * sizeof(node));
		G->Adj[i]->vertexNumber = i;
		G->Adj[i]->next = NULL;
	}
 
	for (i = 0; i < G->E; i++) {
		printf("Enter the edge: ");
		scanf("%d %d", &x,&y);
		temp = (node*)malloc(sizeof(node));
		temp->vertexNumber = y;
        temp->next = NULL;
        
		temp2 = G->Adj[x];
		while (temp2->next != NULL)
			temp2 = temp2->next;
		temp2->next = temp;
		
	}
	return G;
}

void DFSTraversal(Graph* G, int index, int Visited[]) 
{
	node * head;
	head =  G->Adj[index]->next;

	printf("%d ",index);
	
	while(head)
	{
		if(!Visited[head->vertexNumber])
		{
			Visited[head->vertexNumber]=1;
			DFSTraversal(G, head->vertexNumber, Visited);
		}
		head=head->next;
	}
}

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() {
	Graph *G = adjacencyList();
	DFS(G);
}

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

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Using the double hashtag operator in macro expansion