Program to implement Breadth First Search (BFS)
Algorithm
- Place the starting node s on the queue.
- If the queue is empty, return failure and stop.
- If the first element on the queue is a goal node g, return success and stop Otherwise,
- Remove and expand the first element from the queue and place all the children at the end of the queue in any order.
- Return to step 2.Example:Consider a graphSource Code:
#include<stdio.h>#include<conio.h>inta[20][20],q[20],visited[20],n,i,j,f=0,r=-1;voidbfs(intv){for(i=1;i<=n;i++)if(a[v][i] && !visited[i])q[++r]=i;if(f<=r){visited[q[f]]=1;bfs(q[f++]);}}voidmain(){intv;clrscr();printf("\n Enter the number of vertices:");scanf("%d",&n);for(i=1;i<=n;i++){q[i]=0;visited[i]=0;}printf("\n Enter graph data in matrix form:\n");for(i=1;i<=n;i++)for(j=1;j<=n;j++)scanf("%d",&a[i][j]);printf("\n Enter the <span id="IL_AD3" class="IL_AD">starting</span> vertex:");scanf("%d",&v);bfs(v);printf("\n The node which are reachable are:\n");for(i=1;i<=n;i++)if(visited[i])printf("%d\t",i);elseprintf("\n Bfs is not possible");getch();}
No comments:
Post a Comment