From 4b5178d06de383291b993cd86dc9c95fe152864c Mon Sep 17 00:00:00 2001 From: Lavish Swarnkar Date: Sat, 5 Oct 2019 20:30:57 +0530 Subject: [PATCH] Added BFS C program --- bfs.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 bfs.c diff --git a/bfs.c b/bfs.c new file mode 100644 index 0000000..0b73f39 --- /dev/null +++ b/bfs.c @@ -0,0 +1,44 @@ +#include +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; + } + } +} \ No newline at end of file