Code
#include<stdio.h>
#define SIZE 10
int vis[10];
typedef struct
{
int n;
int adj_mat[15][15];
}graph;
graph g;
typedef struct
{
int arr[20],top;
}stack;
stack s;
void init()
{
s.top=-1;
}
int empty()
{
if(s.top==-1)
return 1;
return 0;
}
void push(int curr)
{
s.arr[++s.top]=curr;
}
int pop()
{
return s.arr[s.top--];
}
int top()
{
return s.arr[s.top];
}
void read_graph();
void dfs();
int main()
{
int source;
read_graph();
printf("\nEnter source vertex ");
scanf("%d",&source);
printf("\nDFS = ");
dfs(source);
return 0;
}
void read_graph()
{
int i,j;
printf("Enter the no of vertices in the graph ");
scanf("%d",&g.n);
printf("\nEnter adjacency matrix\n");
for(i=1;i<=g.n;i++)
{
for(j=1;j<=g.n;j++)
scanf("%d",&g.adj_mat[i][j]);
vis[i] = 0;
}
}
void dfs(int source)
{
int curr,i = 1;
vis[source] = 1;
push(source);
printf("%d ",source);
while(!empty())
{
curr = top();
while(i<=g.n)
{
if(vis[i]==0 && g.adj_mat[curr][i]==1)
{
curr = i;
vis[curr] = 1;
push(curr);
printf("%d ",curr);
i = 1;
continue;
}
i++;
}
i = pop();
i++;
}
}
O/P
No comments:
Post a Comment