Implement the DFS Traversals on Graphs.
#include<stdio.h>
#define size 10
int s[10],visited[10],a[10][10],top=-1,n,v,w,st;
void dfs(int st);
void push(int);
int pop();
int instack(int);
int main()
{
int i,j;
printf("\nEnter no of Vertices:");
scanf("%d",&n);
printf("\nEnter Adjacent Matrix From Given Graph:");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
visited[i]=0;
}
}
printf("\nEnter Starting Vertex:");
scanf("%d",&st);
printf("\nDFS Travasal of Given Graph");
dfs(st);
return 0;
}
void dfs(int st)
{
push(st);
while(top!=-1)
{
v=pop();
if(visited[v]==0)
{
visited[v]=1;
printf("->%d",v);
for(w=1;w<=n;w++)
{
if(a[v][w]==1)
{
if(visited[w]==0 && instack(w)==0)
push(w);
}
}
}
}
}
void push(int x)
{
if(top==size-1)
printf("\nOverflow");
else
{
top=top+1;
s[top]=x;
}
}
int pop()
{
int item;
if(top==-1)
return -1;
else
{
item=s[top];
top=top-1;
return item;
}
}
int instack(int w)
{
int j;
for(j=top;j==0;j--)
{
if(s[j]==w)
return 1;
}
return 0;
}
Comments
Post a Comment