Ds 10
Ds 10
10
Implementation of Graph traversal techniques - Depth First
Search
Date of Performance:23/09/24
Date of Submission:30/09/10
Experiment No. 10: Depth First Search and Breath First Search
Aim : Implementation of DFS traversal of graph.
Objective:
1. Understand the Graph data structure and its basic operations.
2. Understand the method of representing a graph.
3. Understand the method of constructing the Graph ADT and defining its operations
Theory:
A graph is a collection of nodes or vertex, connected in pairs by lines referred as edges. A
graph can be directed or undirected graph.
One method of traversing through nodes is depth first search. Here we traverse from
starting node and proceeds from top to bottom. At a moment we reach a dead end from where the
further movement is not possible and we backtrack and then proceed according to left right order.
A stack is used to keep track of a visited node which helps in backtracking.
DFS Traversal –0 1 2 3 4
Algorithm
Algorithm: DFS_LL(V)
Input: V is a starting vertex
Output : A list VISIT giving order of visited vertices during traversal.
Description: linked structure of graph with gptr as pointer
1. if gptr = NULL then
print “Graph is empty” exit
2. u=v
3. OPEN.PUSH(u)
4. while OPEN.TOP !=NULL do
u=OPEN.POP()
if search(VISIT,u) = FALSE then
INSERT_END(VISIT,u)
Ptr = gptr(u)
While ptr.LINK != NULL do
Vptr = ptr.LINK
OPEN.PUSH(vptr.LABEL)
End while
End if
End while
5. Return VISIT
6. Stop
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int label;
} GraphNode;
int numVertices;
GraphNode** adjLists;
} Graph;
int* items;
int top;
int maxSize;
} Stack;
stack->maxSize = size;
stack->top = -1;
return stack;
}
stack->items[++stack->top] = item;
return stack->items[stack->top--];
graph->numVertices = vertices;
graph->adjLists[i] = NULL;
return graph;
newNode->label = dest;
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
if (visited[i] == vertex) {
return true;
return false;
int visitCount = 0;
push(openStack, startVertex);
while (!isEmpty(openStack)) {
visited[visitCount++] = currentVertex;
push(openStack, adjList->label);
adjList = adjList->next;
free(visited);
free(openStack->items);
free(openStack);
int main() {
scanf("%d", &vertices);
scanf("%d", &edges);
int startVertex;
scanf("%d", &startVertex);
DFS(graph, startVertex);
printf("\n");
temp = temp->next;
free(toFree);
free(graph->adjLists);
free(graph);
return 0;
}
Output:
Conclusion: