Experiment 9
Experiment 9
9
Objective: To implement DFS using linked list.
Theory: Depth First Traversal (or DFS) for a graph is similar to Depth First
Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain
cycles (a node may be visited twice). To avoid processing a node more than
once, use a boolean visited array. A graph can have more than one DFS traversal.
The step by step process to implement the DFS traversal is given as follows -
1. First, create a stack with the total number of vertices in the graph.
2. Now, choose any vertex as the starting point of traversal, and push that
vertex into the stack.
3. After that, push a non-visited vertex (adjacent to the vertex on the top of
the stack) to the top of the stack.
4. Now, repeat steps 3 and 4 until no vertices are left to visit from the vertex
on the stack's top.
5. If no vertex is left, go back and pop a vertex from the stack.
6. Repeat steps 2, 3, and 4 until the stack is empty.
Algorithm:
Initialization:
1.1. Define structures:
AdjListNode with fields dest and next.
AdjList with a field head.
Graph with fields V and array.
1.2. Create utility functions:
newAdjListNode(int dest) to create a new adjacency list node.
createGraph(int V) to initialize a graph with V vertices and empty
adjacency lists.
Add Edges:
addEdge(struct Graph* graph, int src, int dest):
o Create a new node with the destination vertex.
o Insert the new node at the beginning of the adjacency list of
the source vertex.
DFS Traversal:
DFSUtil(int v, int visited[], struct Graph* graph):
o Mark v as visited.
o Print v.
o For each adjacent vertex u of v, if u is not visited, recursively
call DFSUtil(u, visited, graph).
DFS(struct Graph* graph, int v):
o Allocate and initialize the visited array to false (0).
o Call DFSUtil(v, visited, graph).
Program:
#include <stdio.h>
#include <stdlib.h>
return graph;
}
// Driver code
int main() {
// Create a graph given in the above diagram
int V = 4;
struct Graph* graph = createGraph(V);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 0);
addEdge(graph, 2, 3);
addEdge(graph, 3, 3);
return 0;
}
Output:
Following is Depth First Traversal (starting from vertex 2)
2301