Ada BFS

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Program to implement the graph Breadth first search algorithm and

estimate the time and space complexity

Step 1: Algorithm design


Algorithm :Breadth First Search(BFS)
Input: n:-no of vertices, A:- nXn adjacency matrix of the input graph

Output: Print all the nodes which are reachable from the starting vertex

Algorithm Time Frequency


for i=1 to n do 3 N+1
If(a[v][i] && !visited[i]) 4 N
Q(++r)=i 3 1
End for
If(f<=r) 1 1
Visited(q[f])=1 3 1
Bfs(q[f++]) 3 1

F=0 1 1
R=-1 1 1
For i=1 to n do 3 N+1
Q[i]=0 2 N
Visited[i]=0 2 N
End for
Bfs(v) 1 1
For i=1 to n do 3 N+1
If(visited[i]) 1 N
Print “i”
End if
End for

Step: 2 :Apriori Analysis

Totaltime=3*(N+1)+4*N+3+1+3+3+1+1+3*(N+1)+2N+2N+1+3*(N+1)+N

=18n+22
Table: n vs T
n Total Time(T)
4 94
5 112
6 130
7 148
8 166
Graph:

Apriori Analysis
180
160
140
120
Axis Title

100
80
60 Series1
40
20
0
1 2 3 4 5
Axis Title

Step 3:Implementation

// Breadth First Search(BFS)

#include<stdio.h>

#include<conio.h>

int a[20][20],q[30],visited[30],n,i,j,f=0,r=-1,t=5;

void bfs(int v)

t=t+1;

for(i=1;i<=n;i++)
{

t=t+6;

if(a[v][i] && !visited[i])

q[++r]=i;

t=t+3;

t=t+1;

if(f<=r)

visited[q[f]]=1;

t=t+3;

bfs(q[f++]);

t=t+3;

void main()

int v;

clrscr();

printf("\nEnter the number of vertices\n");

scanf("%d",&n);

t=t+1;
for(i=1;i<=n;i++)

t=t+2;

q[i]=0;

t=t+2;

visited[i]=0;

t=t+2;

printf("\nEnter graph data in the matrix form\n");

t=t+1;

for(i=1;i<=n;i++)

t=t+2;

for(j=1;j<=n;j++)

t=t+3;

scanf("%d",&a[i][j]);

printf("\nEnter the starting vertex\n");

scanf("%d",&v);

bfs(v);
t=t+1;

printf("\nThe nodes which are reachable are:\n");

t=t+1;

for(i=1;i<=n;i++)

t=t+2;

if(visited[i])

printf("%d\t",i);

printf("\n\nTime complexity=%d\n",t);

printf(“\nSpace complexity=%d\n”,sizeof(a)+ sizeof(q)+ sizeof(visited)+


sizeof(n));

getch();

}
Step 4: Aposteriori analysis:

n t
4
5
6
7
8

You might also like