Advertisement
Guest User

Bfs

a guest
Feb 17th, 2020
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define white 1
  5. #define gray 2
  6. #define black 3
  7.  
  8. char adj[125][125];
  9. char parent[125];
  10. int color[8];
  11. int dis[8];
  12. int path[8];
  13. int n,e;
  14.  
  15.  
  16. void bfs(char snode)
  17. {
  18.     char i,j,x;
  19.     for(i=0;i<n;i++)
  20.     {
  21.         color[i]=white;
  22.         parent[i]=-1;
  23.         dis[i]=-1;
  24.     }
  25.     color[snode]=gray;
  26.     parent[snode]=-1;
  27.     dis[snode]=0;
  28.     queue<char>q;
  29.     q.push(snode);
  30.     while(!q.empty())
  31.     {
  32.         x=q.front();
  33.         q.pop();
  34.         for(i=0;i<n;i++)
  35.         {
  36.             if(adj[x][i]==1)
  37.             {
  38.                 if(color[i]==white)
  39.                 {
  40.                     parent[i]=x;
  41.                     dis[i]=dis[x]+1;
  42.                     q.push(i);
  43.                 }
  44.             }
  45.         }
  46.         color[x]=black;
  47.     }
  48. }
  49. int main()
  50. {
  51.  
  52.   cout<<"Enter no of node and edge:";
  53.   cin>>n>>e;
  54.   char u,v,snode;
  55.   int i;
  56.   cout<<"Enter nodes:\n";
  57.   for(i=1;i<=e;i++)
  58.   {
  59.       cin>>u>>v;
  60.       adj[u][v]=1;
  61.   }
  62.   cout<<"Enter source node:";
  63.   cin>>snode;
  64.   cout<<"path:\n";
  65.   bfs(snode);
  66.  
  67.   return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement