Advertisement
SMASIF

BFS

Jan 29th, 2017
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. #include<iostream>
  2. #include<cstdio>
  3. #include<cmath>
  4. #include<vector>
  5. #include<list>
  6. #include<queue>
  7.  
  8. using namespace std;
  9.  
  10. int v;
  11. int matrix[100][100],clr[100],dis[100],prev[100];
  12. void BFS(int s);
  13.  
  14. int main()
  15.  
  16. {
  17. int r,c,n,s;
  18. int edge=1;
  19. cout<<"Input no of Vertex : "<<endl;
  20. cin>>v;
  21.  
  22. do
  23. {
  24. cout<<"Edge "<<edge<<": "<<endl;
  25. cin>>r>>c;
  26. if(r>v || c>v)
  27. {
  28. cout<<"Invalid Input,Try Again"<<endl;
  29. }
  30.  
  31. else
  32. {
  33. matrix[r][c]=1;
  34. matrix[c][r]=1;
  35. edge++;
  36. }
  37.  
  38. }
  39. while(r!=0 || c!=0);
  40.  
  41. cout<<"Enter the source node: "<<endl;
  42. cin>>s;
  43.  
  44. if(s<1 || s>v){
  45. cout<<"Invalid"<<endl;
  46. }
  47. else
  48. {
  49. BFS(s);
  50. }
  51.  
  52. cout<<endl<<"Vertex no: "<<endl;
  53. for(int g=1; g<=v; g++){
  54. cout<<g<<endl;
  55. }
  56. cout<<endl<<"Colour: "<<endl;
  57. for(int h=1; h<=v; h++){
  58. cout<<clr[h]<<" ";
  59. }
  60. cout<<endl<<"Distance: "<<endl;
  61. for(int m=1; m<=v; m++){
  62. cout<<dis[m]<<" ";
  63. }
  64. cout<<endl<<"Previous: "<<endl;
  65. for(int n=1; n<=v; n++){
  66. cout<<prev[n]<<" ";
  67. }
  68.  
  69. return 0;
  70.  
  71. }
  72.  
  73.  
  74.  
  75.  
  76. void BFS(int s)
  77. {
  78. queue<int> Q;
  79. int i,j,u;
  80. //int clr[100],dis[100],prev[100];
  81. for(i=1; i<=v; i++)
  82. {
  83. clr[i]=0;
  84. dis[i]=1500000000;
  85. prev[i]=-1;
  86. }
  87.  
  88. clr[s]=1;
  89. dis[s]=0;
  90. Q.push(s);
  91.  
  92. while(!Q.empty())
  93. {
  94. u = Q.front();
  95. Q.pop();
  96. for(i=1;i<=v;i++)
  97. {
  98. if(matrix[u][i]==1 && clr[i]==0)
  99. {
  100. clr[i]=1;
  101. dis[i]=dis[u]+1;
  102. prev[i]=u;
  103. Q.push(i);
  104. }
  105. }
  106.  
  107. clr[u]=2;
  108. }
  109.  
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement