Advertisement
Guest User

Bfs

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