My Profile

I, Das ShrikKrishna J. MCA III IMSCD&R, Ahmednagar.

Monday, 15 August 2011

DFS

#include<stdio.h>
#include<conio.h>
struct stack {
int data[20];
int top;
} s1;
void push(int n)
{
s1.data[++s1.top]=n;
}
int pop()
{
return s1.data[s1.top--];
}
void initstack()
{
s1.top=-1;
}
int emptystack()
{
return(s1.top==-1);
}
void dfs(int m[10][10],int n)
{
int i,v,w;
int visited[20]={0};
initstack();
v=0;
visited[v]=1;
push(v);
printf("%d\t",v+1);
while(1)
{
for(w=0;w<n;w++)
{
if((m[v][w]==1)&&(visited[w]==0))
{
push(w);
printf("%d\t",w+1);
visited[w]=1;
}
}
if(emptystack())
break;
else
v=pop();
}
}
void recdfs(int m[10][10],int n,int v)
{
int w;
static int visited[20]={20};
visited[v]=1;
printf("%d\t",v+1);
for(w=0;w<n;w++)
{
if((m[v][w]==1)&&(visited[w]==0))
{
recdfs(m,n,w);
}
}
}
void main()
{
int m[10][10],i,n,j;
clrscr();
printf("how many vertices");
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
m[i][j]=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(i!=j)
{
printf(" Is there any edge between vertex %d & %d (1/0)",i+1,j+1);
scanf("%d",&m[i][j]);
}
}
clrscr();
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",m[i][j]);
//else
//printf("0");
}
printf("\n");
}
printf("\nRECURSIVE DFS IS");
printf("\n");
recdfs(m,n,0);
printf("\nNON RECURSIV DFS IS");
printf("\n");
dfs(m,n);
getch();
}

No comments:

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | cheap international calls