0% found this document useful (0 votes)
47 views3 pages

Program To Implement Breadth First Search and Depth First Search in A Graph

This document contains code to implement breadth-first search (BFS) and depth-first search (DFS) algorithms on a graph. It defines functions for BFS and DFS that take in a graph represented by cost matrix, perform the search, and output the visited vertices. The main function provides a menu to call either BFS or DFS and exit the program.

Uploaded by

Amay Rajvaidya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views3 pages

Program To Implement Breadth First Search and Depth First Search in A Graph

This document contains code to implement breadth-first search (BFS) and depth-first search (DFS) algorithms on a graph. It defines functions for BFS and DFS that take in a graph represented by cost matrix, perform the search, and output the visited vertices. The main function provides a menu to call either BFS or DFS and exit the program.

Uploaded by

Amay Rajvaidya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Program to implement breadth first search and depth first search in a graph

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int cost[10][10],i,j,k,n,qu[10],front,rear,v,visit[10],visited[10],stack[10],top;
void BFS()
{
int m;
cout<<"Enter no of Vertices : ";
cin>>n;
cout<<"Enter no of edges : ";
cin>>m;
cout<<"\nEdges \n";
for(k=1;k<=m;k++)
{
cin>>i>>j;
cost[i][j]=1;
}
cout<<"Enter initial vertex : ";
cin>>v;
cout<<"Visited vertices \n";
cout<<v;
visited[v]=1;
k=1;
while(k<n)
{
for(j=1;j<=n;j++)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
qu[rear++]=j;
}
v=qu[front++];
cout<<v<< " ";
k++;
visit[v]=0;
visited[v]=1;
}
}

void DFS()
{
int m;
cout<<"Enter no of Vertices : ";
cin>>n;
cout<<"Enter no of edges : ";
cin>>m;
cout<<"\nEdges \n";
for(k=1;k<=m;k++)
{
cin>>i>>j;
cost[i][j]=1;
}
cout<<"Enter initial vertex : ";
cin>>v;
cout<<"Visited vertices \n";
cout<<v;
visited[v]=1;
k=1;
while(k<n)
{
for(j=n;j>=1;j--)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
stack[top]=j;
top++;
}
v=stack[--top];
cout<<v<< " ";
k++;
visit[v]=0;
visited[v]=1;
}
}

void main()
{
clrscr();
int ch;
cout<<"\n1. Breadth first search\n2. Depth first search\n3. Exit";
while(1)
{
cout<<"\nEnter your choice";
cin>>ch;
switch(ch)
{
case 1 : BFS();break;
case 2 : DFS();break;
case 3 : exit(0);
default : cout<<"\nInvalid choice" ;
}
}
getch();
}

You might also like