#include<conio.h> #include<iostream.h> #include<stdlib.

h> void create(); // For creating a graph void dfs(); // For Deapth First Search(DFS) Traversal. void bfs(); // For Breadth First Search(BFS) Traversal. struct node // Structure for elements in the graph { int data,status; struct node *next; struct link *adj; }; struct link // Structure for adjacency list { struct node *next; struct link *adj; }; struct node *start,*p,*q; struct link *l,*k; int main() { int choice; clrscr(); create(); while(1) { cout<<" -----------------------"; cout<<" 1: DFS 2: BSF 3: Exit Enter your choice: "; cin>>choice; switch(choice) { case 1: dfs(); break; case 2: bfs(); break; case 3: exit(0); break; default: cout<<" Incorrect choice! Re-enter your choice."; getch(); } } return 0; }

start=NULL. if(flag==0) { start=p.void create() // Creating a graph { int dat. flag++. if(flag==0) { p->adj=k. l=k. while(p!=NULL) { cout<<"Enter the links to "<<p->data<<" (0 to end) : ". } } p=start. if(dat==0) break. while(q!=NULL) { if(q->data==dat) k->next=q. } } .flag=0. while(1) { cin>>dat. p->next=NULL. k->adj=NULL. p->adj=NULL. if(dat==0) break. l=k. while(1) { cin>>dat. flag++. p->status=0. } q=start. } else { l->adj=k. flag=0. q=p. k=new link. } else { q->next=p. p->data=dat. cout<<" Enter the nodes in the graph(0 to end): ". q=p. q=q->next. p=new node.

} j=0. p->status=1. } k=k->adj. qu[i+1]=0. while(1) { if(qu[j]==0) break. } cout<<" -------------------------". } // Deapth First Search(DFS) Traversal. cout<<" Breadth First Search Results ". } p=start. while(p!=NULL) { p->status=0. while(p!=NULL) { if(p->data==qu[j]) break. i++.i=1. j++. . cout<<" --------------------------". qu[0]=p->data. } j++. while(qu[j]!=0) { cout<<qu[j]<<" ". p=start.p=p->next. p=p->next. q->status=1. void bfs() { int qu[20]. p=p->next. return. } k=p->adj.j=0. if(q->status==0) { qu[i]=q->data. while(k!=NULL) { q=k->next. p=start.

p=start. p=p->next. } . cout<<" --------------------------". p->status=1. return. while(p!=NULL) { p->status=0. stack[top]=q->data. p=start. } // Breadth First Search(BFS) Traversal. k=p->adj. cout<<" Deapth First Search Results ". stack[top]=p->data. return. while(k!=NULL) { q=k->next. p=p->next. } } getch(). } p=start. while(1) { if(stack[top]==0) break.} getch(). if(q->status==0) { top++. stack[0]=0. void dfs() { int stack[25].top=1. } cout<<stack[top]<<" ". while(p!=NULL) { if(p->data==stack[top]) break. top--. q->status=1. } k=k->adj.

Sign up to vote on this title
UsefulNot useful