DFS and BFS
DFS and BFS
#include<stdio.h>
#include<conio.h> //header files
#include<iostream.h>
#include<process.h>
int A[10][10],visited[10];
void main()
{ int n,i,j,snode;
printf("\nEnter the no.of nodes\n");
cin >> n;
printf("Enter the adjacency matrix ");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&A[i][j]);
while(1)
{ for(j=1;j<=n;j++)
{ if(A[u][j]==1) //if u is adjacent
{ if(visited[j]==0) //if u has not been visited
q[++r] = j;
visited[j]=1;
}
}
if(f > r) return;
u= q[f++];
cout<<u<<"\t";
}
}
OUTPUT
Enter the no.of nodes
8
Enter the adjacency matrix
011000 00
000110 00
0000011 0
0000000 1
0000000 1
0000000 1
000 00001
0000000 0
Enter the starting node:
1
The nodes reachable are
1 2 3 4 5 6 7 8
PROGRAM No. 7b
#include<stdio.h>
#include<conio.h>
#include<process.h>
int n,a[10][10];
/*This function accepts v as the initial vertex to start with. It
then finds if its child is visited. If it is not visited, then
it visits the child and recursively calls with the child as
the argument. */
void DFS(int visit[],int v) //recursive depth-first search
{ int i; visit[v]=1;
printf("%d ",v);
for( i=1;i<=n;i++)
{ if(a[v][i]==1) //if path exists
{
if(visit[i]==0) //if the node has not been visited
DFS(visit,i);
}
}
}
void main() //main function
{ int visit[10],i,j,k;
clrscr();
printf("\nEnter the no. of nodes\n");
scanf("%d",&n);
printf("Enter the adjacency matrix ");
for( i=1;i<=n;i++)
for( j=1;j<=n;j++) scanf("%d",&a[i]
[j]);
for( i =1; i <=n; i++)
{ for(j=1;j<=n;j++)
visit[j]=0;
printf(" \nthe nodes reachable from node %d is ",i);
DFS(visit,i); //call
DFS for(k =1; k<=n;k++)
if(visit[k] == 0)
{ printf("graph is not connected");
exit(0);
}
}
printf("graph is connected\n");
}
OUTPUT
Enter the no. of nodes
4
Enter the adjacency matrix
0100
0010
0001
1000
the nodes reachable from node 1 is 1 2 3 4
the nodes reachable from node 2 is 2 3 4 1
the nodes reachable from node 3 is 3 4 1 2
the nodes reachable from node 4 is 4 1 2 3
graph is connected