Waliullah8328

BFS

Aug 4th, 2021
862
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<stdio.h>
  2. void bfs(int v);
  3.  
  4. int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
  5.  
  6. int main() {
  7.     int v;
  8.     //Enter the number of vertices
  9.     scanf("%d",&n);
  10.     //initialization loop
  11.     for (i=1;i<=n;i++) {
  12.         q[i]=0;
  13.         visited[i]=0;
  14.     }
  15.     //Enter graph data in matrix form
  16.     for (i=1;i<=n;i++)
  17.       for (j=1;j<=n;j++)
  18.        scanf("%d",&a[i][j]);
  19.     //Enter the starting vertex
  20.     scanf("%d",&v);
  21.     q[++r]=v;
  22.     bfs(v);
  23.  
  24.     return 0;
  25. }
  26.  
  27. void bfs(int v) {
  28.     for (i=1;i<=n;i++)
  29.       if(a[v][i] && !visited[i]){
  30.        q[++r]=i;
  31.       }
  32.     if(f<=r) {
  33.         if(visited[q[f]]==0)
  34.             printf("%d\t",q[f]);
  35.         visited[q[f]]=1;
  36.         bfs(q[f++]);
  37.     }
  38. }
RAW Paste Data