Advertisement
Guest User

BFS

a guest
Jul 19th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.82 KB | None | 0 0
  1. #include<stdio.h>
  2. int a[20][20], q[20], visited[20], n, i, j,
  3.  f = 0,
  4.  r = -1;
  5.  
  6. void bfs(int v) {
  7.     for(i = 1; i <= n; i++)
  8.         if(a[v][i] && !visited[i])
  9.             q[++r] = i;
  10.     if(f <= r) {
  11.         visited[q[f]] = 1;
  12.         bfs(q[f++]);
  13.     }
  14. }
  15.  
  16. void main() {
  17.     int v;
  18.     printf("\n Enter the number of vertices:");
  19.     scanf("%d", &n);
  20.  
  21.     for(i=1; i <= n; i++) {
  22.         q[i] = 0;
  23.         visited[i] = 0;
  24.     }
  25.  
  26.     printf("\n Enter graph data in matrix form:\n");
  27.     for(i=1; i<=n; i++) {
  28.         for(j=1;j<=n;j++) {
  29.                
  30.             scanf("%d", &a[i][j]);
  31.         }
  32.     }
  33.  
  34.     printf("\n Enter the starting vertex:");
  35.     scanf("%d", &v);
  36.     bfs(v);
  37.     printf("\n The node which are reachable are:\n");
  38.  
  39.     for(i=1; i <= n; i++) {
  40.         if(visited[i])
  41.             printf("%d\t", i);
  42.         else {
  43.             printf("\n Bfs is not possible. Not all nodes are reachable");
  44.             break;
  45.         }
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement