Prem Tiwari - - C Programming Tutorial

Here is a c program to describe the BFS (Breadth First Search). Breadth First Search is an algorithm which is used to search a Tree or Graph in the programming language. It starts from the Root node and then starts traversing to the next level of Tree and Graph.

Also Read:

Copy the below program and execute it with the help of turbo c or TC bin to see the output.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #include<stdio.h> int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1; void bfs(int v) { 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++]); } } void main() { int v; 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 starting 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); else { printf("\n Bfs is not possible. Not all nodes are reachable"); break; } } } |

Enter the number of vertices:3

Enter graph data in matrix form:

2

4

5

2

3

4

1

7

8

Enter the starting vertex:2

The node which are reachable are:

1 2 3

Prem Tiwari is the founder of FreeWebMentor.com and also a professional developer who has vast experience in PHP and open source technologies. Apart from this, he is a blogger by hobby and also he has been a regular speaker of WordPress sessions in various IT Companies. View all posts by Prem Tiwari

Tags: bfs code c, bfs implementation in c, breadth first search c code, breadth first search code in c, breadth first search program in c, c program for breadth first search

We use cookies to ensure that we give you the best experience and deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.OkPrivacy policy