Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 2

// Program to implement Depth-First-Search (DFS)

#include<stdio.h> #include<conio.h> #include<stdlib.h> #define MAX 100 void dfs(int n); void dfs_visit(int u); int color[MAX]; int d[MAX]; int f[MAX]; int time; typedef struct vert* ver; struct vert { int ident; ver next; } cor; ver adj_list[MAX]; void main() { int n,i,j,k; ver temp,prev; clrscr(); printf("Enter no of nodes : "); scanf("%d",&n); for(i=0;i<=n;i++) adj_list[i]='\0'; for(i=1;i<=n;i++) { prev=NULL; printf("Enter No of vertex connected to %d :",i); scanf("%d",&j); for(k=0;k<j;k++) { temp=(ver)malloc(sizeof(cor)); temp->next=NULL; printf("Enter Vertex No. connected to vertex %d : ",i); scanf("%d",&temp->ident); if(prev==NULL) adj_list[i]=temp; else

prev->next=temp; prev=temp; } } dfs(n); for(i=1;i<=n;i++) { printf("\nStarting/Ending time of Vertex %d is %d/%d",i,d[i],f[i]); } getch(); } void dfs(int n) { int i; for(i=1;i<=n;i++) color[i]=0; time=0; for(i=1;i<=n;i++) { if(color[i]==0) dfs_visit(i); } } void dfs_visit(int u) { ver temp; color[u]=1; time++; d[u]=time; temp=adj_list[u]; while(temp!=NULL) { if(color[temp->ident]==0) dfs_visit(temp->ident); temp=temp->next; } color[u]=2; f[u]=++time; }

You might also like