The BOTTOM LINE Quote Of The Day

The BOTTOM LINE Quote Of The Day

Don't Ever Tell GOD How BIG Your Problems are.
Just Tell Your Problems How BIG your GOD is ;)

Tuesday, March 1, 2011

Breadth and Depth First Search (BFS and DFS) Algorithms (Simple)


#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#include"graph01.cpp"      /* Refer this Source Code */
#define max 50

struct queue
{
 int front;
 int rear;
 struct node *ver[max];
}qu;

struct stack
{
 int top;
 struct node *ver[max];
}stk;


void BFS()
{
 qu.front = qu.rear = 1;
 if(loc != NULL)
 {
  loc->status = 2;
  qu.ver[qu.front] = loc;
 }
 else
  printf("\n\n Node not found !!\n\n");
 printf("\n\n The BFS Traversal Is : ");
 while(qu.front != 0)
 {
  loc = qu.ver[qu.front];
  printf(" %c",loc->info);
  loc->status = 3;
  qu.front++;
  ptre = loc->adj;
  while(ptre!=NULL)
  {
   if(ptre->dest->status == 1)
   {
    ptre->dest->status = 2;
    qu.rear += 1;
    qu.ver[qu.rear] = ptre->dest;
   }
  ptre = ptre->link;
  }
  if(qu.front > qu.rear)
   qu.front = 0;
 }
}

void DFS()
{
 stk.top = 1;
 if(loc != NULL)
 {
  loc->status = 2;
  stk.ver[stk.top] = loc;
 }
 else
  printf("\n\n Node not found !!\n\n");
 printf("\n\n The DFS Traversal Is : ");
 while(stk.top != 0)
 {
  loc = stk.ver[stk.top--];
  printf(" %c",loc->info);
  loc->status = 3;
  ptre = loc->adj;
  while(ptre!=NULL)
  {
   if(ptre->dest->status == 1)
   {
    ptre->dest->status = 2;
    stk.ver[++stk.top] = ptre->dest;
   }
  ptre = ptre->link;
  }
 }
}

void main()
{
clrscr();
create_node();
create_vertices();
printf("\n\n Enter the starting node : ");
cin>>item;
find_node();
int_stats();
BFS();
find_node();
int_stats();
DFS();
getch();
}

No comments:

Post a Comment