Assignment No:: Problem Statement:-Theory
Assignment No:: Problem Statement:-Theory
ASSIGNMENT NO:
PROBLEM STATEMENT:- C program to find the DFS traversal of a
given graph.
THEORY:- Depth First Traversal(or search) for a graph is similar to
Depth First Traversal of a tree . The only catch here is, unlike trees, graphs
may contain cycles, so we may come to the same node again. To avoid
processing a node more than once, we use a Boolean visited array.
For example, in the following graph, we start traversal from vertex 2. When we come
to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If
we don’t mark visited vertices, then 2 will be processed again and it will become a
non-terminating process. A Depth First Traversal of the following graph is 2, 0, 1, 3.
ALGORITHM:-
Variable Name Type Purpose
Date:
Page No.
SOURCE CODE: -
#include<stdio.h>
Date:
Page No.
int DFS(int);
int G[10][10],visited[10],n;
int main()
{
int i,j,n;
scanf("%d",&G[i][j]);
}
}
for(i=0;i<n;i++)
{
visited[i]=0;
printf("\n\n required DFS for above graph is");
DFS(0);
return 0;
}
}
int DFS(int i)
Date:
Page No.
{
int j;
printf("\n %d",i);
visited[i]=1;
for(j=0;j<n;i++)
{
if(!visited[j]&&G[i][j]==1)
DFS(j);
Date:
Page No.
7
2
3
6
8
4
DISCUSSIONS: -
1. The above code traverses only the vertices reachable from a given source vertex. All
the vertices may not be reachable from a given vertex (example Disconnected
graph). To do complete DFS traversal of such graphs, we must call DFS() for every
vertex.
Date:
Page No.
2. Also, before calling DFS(), we should check if it is already printed by some other call
of DFS(). Above implementation does the complete graph traversal even if the nodes
are unreachable.
Date: